1

Im having trouble getting the type of song in an xml file. First off I am loading in the XML file using

$xmlDoc = file_get_contents('/songs.xml');

once the file has been loaded into a string I explode them into an array using

$songs = explode("<song>", $xmlDoc);

I have tried using a foreach loop to step through each song then exploding the type, however this isn't giving me just the type it's including Rock</type>.

songs.xml

<songs>
    <song>
        <title>Paradise City</title>
        <artist>Guns & Roses</artist>
        <type>Rock</type>
    </song>
    <song>
        <title>One Love</title>
        <artist>Bob Marley</artist>
        <type>Reggae</type>
    </song>
    <song>
        <title>Sweet Child Mine</title>
        <artist>Guns & Roses</artist>
        <type>rock</type>
    </song>
</songs>
Kevster
  • 13
  • 4
  • 3
    There are XML parsers for a reason, use them. E.g. [SimpleXML](http://php.net/simplexml) or [DOM](http://php.net/dom). – Jonnix Jun 09 '17 at 14:06
  • @JonStirling thanks, will look into SimpleXML and update on my findings just starting php. – Kevster Jun 09 '17 at 14:08

1 Answers1

0

You need to use a SimpleXMLElement or DomDocument

Example from W3C : https://www.w3schools.com/php/php_xml_simplexml_read.asp

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )

After that, you can parse the "xml" like an array. Enjoy

Xenofexs
  • 511
  • 4
  • 14
  • once this is in an array do I just use the foreach loop and access the items with the key for example `item['type']` Thanks for the help – Kevster Jun 09 '17 at 14:11