How to select the first element of xml

0

I have the following xml:

<SONG>
<PLAYEDAT>1487812025</PLAYEDAT>
<TITLE>John Legend - Love Me Now</TITLE>
<METADATA>
<TIT2>John Legend - Love Me Now</TIT2>
</METADATA>
</SONG>
<SONG>
<PLAYEDAT>1487811800</PLAYEDAT>
<TITLE>Ed Sheeran - Sing</TITLE>
<METADATA>
<TIT2>Ed Sheeran - Sing</TIT2>
</METADATA>
</SONG>
<SONG>
<PLAYEDAT>1487811572</PLAYEDAT>
<TITLE>Maroon 5 - Animals</TITLE>
<METADATA>
<TIT2>Maroon 5 - Animals</TIT2>
</METADATA>
</SONG>

And the following php:

foreach ($songs->SONGHISTORY->SONG as $song){
    $exp = explode(' - ', $song->TITLE);
    $json[] = array(
        'data' => $song->PLAYEDAT,
        'artista' => $exp[0],
        'musica' => $exp[1],
        'itunes' => $song->TITLE
    );
}

However, I have a problem, I can not select a specific SONG , would you like to select only the first SONG , how can I do this? >

    
asked by anonymous 23.02.2017 / 02:10

2 answers

1

As quoted by @ humberto-tecnoboy, there is a flaw in its XML because it does not have a root element:

<?xml version="1.0" encoding="utf-8"?> <SONGS> <SONG> <PLAYEDAT>1487812025</PLAYEDAT> <TITLE>John Legend - Love Me Now</TITLE> <METADATA> <TIT2>John Legend - Love Me Now</TIT2> </METADATA> </SONG> <SONG> <PLAYEDAT>1487811800</PLAYEDAT> <TITLE>Ed Sheeran - Sing</TITLE> <METADATA> <TIT2>Ed Sheeran - Sing</TIT2> </METADATA> </SONG> <SONG> <PLAYEDAT>1487811572</PLAYEDAT> <TITLE>Maroon 5 - Animals</TITLE> <METADATA> <TIT2>Maroon 5 - Animals</TIT2> </METADATA> </SONG> </SONGS>

From here (since XML already has a valid structure), simply load the file into a DOMDocument object, making sure that the contents of tabs, spaces, and other visual only formations are ignored by assigning the preserveWhiteSpace attribute to false , and if you use the tag set as the name you are fetching from the getElementsByTagName method, with this, access the first item of this set:

  

23.02.2017 / 04:30
1

XML needs to be modified:

$PLAYLIST=
"<PLAYLIST>
    <SONG>
        <PLAYEDAT>1487812025</PLAYEDAT>
        <TITLE>John Legend - Love Me Now</TITLE>
        <METADATA>
            <TIT2>John Legend - Love Me Now</TIT2>
        </METADATA>
    </SONG>
    <SONG>
        <PLAYEDAT>1487811800</PLAYEDAT>
        <TITLE>Ed Sheeran - Sing</TITLE>
        <METADATA>
            <TIT2>Ed Sheeran - Sing</TIT2>
        </METADATA>
    </SONG>
    <SONG>
        <PLAYEDAT>1487811572</PLAYEDAT>
        <TITLE>Maroon 5 - Animals</TITLE>
        <METADATA>
            <TIT2>Maroon 5 - Animals</TIT2>
        </METADATA>
    </SONG>
</PLAYLIST>";

$xml=simplexml_load_string($PLAYLIST);

foreach($xml->SONG as $song)
{
    echo "<pre>".print_r($song, true)."</pre>";
}
    
23.02.2017 / 02:57