Search code examples
phpsqlxmlxpathgetelementsbytagname

XMLDoc GetElementsByTagName Only First Entry


I am creating an XML to SQL file using php but only want my script to process the first entry in the XML document

$xmlObject = $xmlDoc->getElementsByTagName('PlaylistEntry');

inputting the specific path that I want

/Playlist/PlaylistEntry[1]/Title[1]/text()

does not produce results.

Any advice?

edit:

$xmlDoc = new DOMDocument();
$xmlDoc->load("file.xml");

$mysql_hostname = "";
$mysql_user     = "";
$mysql_password = "";
$mysql_database = "";

$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Error");
mysql_select_db($mysql_database, $bd) or die("Error");

$xmlObject = $xmlDoc->getElementsByTagName('PlaylistEntry');
$itemCount = $xmlObject->length;

for ($i=0; $i < $itemCount; $i++){
$Title = $xmlObject->item($i)->getElementsByTagName('Title')->item(0)->childNodes->item(0)->nodeValue;
$sql   = "INSERT INTO `nowplaying` (Title) VALUES ('$Title')";
mysql_query($sql);
print "Finished Item $Title<br/>";
}

xml:

<Playlist>
<Refresh>41</Refresh>
<PlaylistEntry>
<Title>Tongue Tied</Title>
<Artist>Grouplove</Artist>
<Album>Never Trust A Happy Song</Album>
<ECommerceURL/>
<FileName>02_Tongue_Tied.mp3</FileName>
<trackType/>
<desc/>
<clickThruURL/>
<visualURL>
id=14245829|img=http://upload.wikimedia.org/wikipedia/en/f/f9/GrouploveTongueTied.jpg
</visualURL>
<Seconds>218</Seconds>
</PlaylistEntry>
<PlaylistEntry>
<Title>Holy Roller Novocaine</Title>
<Artist>Kings of Leon</Artist>
<Album>Kings of Leon EP</Album>
<ECommerceURL/>
<FileName>03_Holy_Roller_Novocaine.mp3</FileName>
<trackType/>
<desc/>
<clickThruURL/>
<visualURL>
id=18144083|img=http://upload.wikimedia.org/wikipedia/en/8/86/Holyrollernovacaine.jpg
</visualURL>
<Seconds>257</Seconds>
</PlaylistEntry>
<PlaylistEntry>
...

Solution

  • Replace

    $xmlObject = $xmlDoc->getElementsByTagName('PlaylistEntry');
    $itemCount = $xmlObject->length;
    
    for ($i=0; $i < $itemCount; $i++){
    $Title = $xmlObject->item($i)->getElementsByTagName('Title')->item(0)->childNodes->item(0)->nodeValue;
    

    by this code using xpath

    $xpath = new DOMXpath($xmlDoc);
    $elements = $xpath->query("/Playlist/PlaylistEntry/Title/text()");
    
    if (!is_null($elements)) 
      foreach ($elements as $element) 
        $Title = $element->wholeText;