Newb question involving DOMDocument and XPath queries

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
maxpagels
Forum Newbie
Posts: 1
Joined: Fri Apr 25, 2008 3:37 am

Newb question involving DOMDocument and XPath queries

Post by maxpagels »

Hello,

I'm relatively new to PHP and have a simple question.

I'm trying print the name of the first artist in an XML file. Here's and excerpt of the file:

Code: Select all

 
<recenttracks>
<track streamable="true">
            <artist mbid="95e1ead9-4d31-4808-a7ac-32c3614c116b">The Killers</artist>
    <name>Read My Mind</name>
    <mbid></mbid>
    <album mbid="">Sam's Town</album>
    <url>http://www.last.fm/music/The+Killers/_/Read+My+Mind</url>
            <date uts="1209110890">25 Apr 2008, 08:08</date>
</track>
<track streamable="true">
            <artist mbid="8538e728-ca0b-4321-b7e5-cff6565dd4c0">Depeche Mode</artist>
    <name>Everything Counts</name>
    <mbid></mbid>
    <album mbid="b8cdaddb-d19e-41fa-8b93-fba58d160d4b">Construction Time Again</album>
    <url>http://www.last.fm/music/Depeche+Mode/_/Everything+Counts</url>
            <date uts="1209110649">25 Apr 2008, 08:04</date>
</track>
</recenttracks>
 
I'm using XPath for this, in conjunction with the DOMDocument object. Problem is, when I execute this PHP code

Code: Select all

 
$doc = new DOMDocument();
        $doc->load("http://ws.audioscrobbler.com/1.0/user/$username/recenttracks.xml");
        $xpath = new DOMXPath($doc);
        $query = "/recenttracks/track[1]/artist";
        $lastplayedtracks = $xpath->query($query);
        echo $lastplayedtracks->item(0)->nodeValue;
 
The artist name is printed twice (eg. "The KillersThe Killers"). This could be a problem with the XPath query, but I don't think so. I'm thinking the DOMNodeList returned by the query($query) function call is the culprit.

How can I modify the above code to only print the artist name once? Help is greatly appreciated.
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: Newb question involving DOMDocument and XPath queries

Post by EverLearning »

I tried your code and it echoed the artist name only once, like it should. Are you sure your xml file and your code aren't different form the code you posted here?
Post Reply