Question

I'm trying to parse the Last.fm feed of my last 10 tracks played onto my website.

This is what I have so far,


<?php

    $doc = new DOMDocument();
    $doc->load('http://ws.audioscrobbler.com/1.0/user/nathanjmassey/recenttracks.xml');
    $arrFeeds = array();
    foreach ($doc->getElementsByTagName('track') as $node) {
        $itemRSS = array ( 
            'artist' => $node->getElementsByTagName('artist')->item(0)->nodeValue,
            'name' => $node->getElementsByTagName('name')->item(0)->nodeValue,
            'url' => $node->getElementsByTagName('url')->item(0)->nodeValue,
            );
        array_push($arrFeeds, $itemRSS);
    }

?>

<?php 

foreach ($arrFeeds as $i => $values) {

    foreach ($values as $key => $value) {
        print "<p>$value\n</p>";  
    }

}

?>

This basically gives me all 10 tracks in the feed in the format,

Linkin Park

In Between

http://www.last.fm/music/Linkin+Park/_/In+Between

But I need to format the results in list of links such as,

<a href="$url">$artist - $track</a>

How would I extend my script to achieve this?

Was it helpful?

Solution

For your output, use this:

<?
foreach ($arrFeeds as $i => $values)
{
    print "<a href='" . $values['url'] . "'>" . $values['artist'] . " - " . $values['name'] . "</a>";
}
?>

UPDATE: How to limit # of parsed items

(Responding to the comment via edit so I can use the code display tags.)

I'm at work at the moment, but I'd try changing your initial parsing code something like so:

array_push($arrFeeds, $itemRSS); // existing line
if (count($arrFeeds) >= 5) { break; } // add this line
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top