Hey Guys, I've been having a bit of a play with the last.fm API and parsing that information. I'm wondering if there's a simple way to get simpleXML look at only the last node. The XML I'm playing with is here -> http://ws.audioscrobbler.com/2.0/?method=user.getartisttracks&user=rj&artist=metallica&api_key=b25b959554ed76058ac220b7b2e0a026. (that's their example API call, it's not my API key, or user etc).

Now I'm wanting to pull the very last entry on that page in order to determine when they first started listening to the artist. I'm interested in the <date> field specifically. Does anyone know how to get simple XML to look at just the last entry, I know I could just write a foreach loop and iterate right the way through, but it doesnt seem very efficient. Any better ways?

<track> 
        <artist mbid="65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab">Metallica</artist> 
<name>Broken, Beat &amp; Scarred</name> 
<streamable>0</streamable> 
<mbid></mbid> 
<album mbid="940d6fba-3603-4ac2-8f5d-ea0a11e51765">Death Magnetic</album> 
<url>http://www.last.fm/music/Metallica/_/Broken%252C%2BBeat%2B%2526%2BScarred</url> 
    <image size="small">http://userserve-ak.last.fm/serve/34s/37283587.jpg</image> 
    <image size="medium">http://userserve-ak.last.fm/serve/64s/37283587.jpg</image> 
    <image size="large">http://userserve-ak.last.fm/serve/126/37283587.jpg</image> 
    <image size="extralarge">http://userserve-ak.last.fm/serve/300x300/37283587.jpg</image> 
        <date uts="1231846623">13 Jan 2009, 11:37</date> 
</track> 

Cheers

    Assuming you've got the XML loaded in a var called $xml, simply treat $xml->artisttracks->track as if it were an array and directly access the last element (hint: they're numerically indexed, so [man]count/man the items and subtract one).

    EDIT: Alternatively, you could also use an XPath expression such as 'artisttracks/track[last()]' .

      hmmm, simple as that eh. It had slipped my mind that methods to determine the last value in an array wouldn't apply to an XML array 🙂 Works well.

      For completion:

      $last_track = count($xml) - 1;
      $xml->artisttracks[0]->track[$last_track]->date

      Thanks for your help.

        Write a Reply...