As quoted by @Humberto-tecnoboy, there is a flaw in your XML as 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 (considering that XML already has a valid structure) just load the file into an object Domdocument, making sure that the content of tabulations, spaces and other visual only formations are ignored by assigning to the attribute preserveWhiteSpace the value false, and use the capture of the set of tags as the name that is being searched through the method getelementsbytagname, with this, access the first item of this set:
<?php
$xml = new Domdocument();
$xml->preserveWhiteSpace = false;
$xml->load('. /Song.xml');
echo ''
, $xml->getelementsbytagname('SONG')->item(0)->getelementsbytagname('PLAYEDAT')->item(0)->nodeValue
, "\n"
, $xml->getelementsbytagname('SONG')->item(0)->getelementsbytagname('TITLE')->item(0)->nodeValue
, "\n"
, $xml->getelementsbytagname('SONG')->item(0)->getelementsbytagname('METADATA')->item(0)->getelementsbytagname('TIT2')->item(0)->nodeValue
, "\n"
;
Note: the TIT2 node could have been obtained appeals searching for the Value node of its top node (METADATA) since it is the only child node, but I did it this way only to follow the pattern of searching for the first occurrence of a node from the tag name
Have you tried, instead of iterating over the list, to run the same code only on
$songs->SONGHISTORY->SONG[0]
?– Woss
Yes, returns no value.
– Paulo Sérgio Filho
But by
foreach
works?– Woss
No, it doesn’t work at all.
– Paulo Sérgio Filho
Then edit your question, enter the entire code and indicate which error is giving.
– Woss
Opa, I got friend, I used json and I managed to manipulate xml, thanks for the help!
– Paulo Sérgio Filho