Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Display Last 5 Songs Played On Last.fm Using PHP

Display Last 5 Songs Played On Last.fm Using PHP

Learn how to create a simple PHP class to load the last 5 played tracks from your Last.fm account.

View an Example of this article before you get started.

I am sure you are all familiar with Last.fm, the premier online music catalogue where you can track your music habits across many devices. Well in this tutorial you are going to learn how to utilize the Last.fm API using PHP to display the last 5 songs played. This tutorial was written with PHP5 in mind, but *most* of it can be adapted to older versions as needed. cURL is used to avoid the recent file system limitations imposed by PHP5. Okay, lets get started.

Before we can begin coding you need to login/sign up to Last.fm and apply for an API key using their automated system. Assuming you have logged in, navigate to "http://www.last.fm/api/account" and request an API key, as shown in figure 1. Once you have created an API key it will be displayed, make note of the "API Key" and ignore the "secret" for now. An example API Key is shown in figure 2.


Figure 1. Create an API Request.


Figure 2. Sample API Key, your actual key will be displayed once created.

Alright great, now that you have an API Key, lets write the script. Begin by creating the basic class and properties to be used later. We will use sprintf to populate the url, so simply place a %s in the url to be replaced.

<?php

class LFM_RecentlyPlayed
{
  public $songs = array();

  public $user = "";
  public $apiurl = "http://ws.audioscrobbler.com/2.0/"
	. "?method=user.getrecenttracks&user=%s&api_key=%s&limit=4";

For simplicity the majority of this script will be located within the __construct() which will run the script once its initialized. Using curl_init() you need to request the Last.fm data, passing in the now formatted url as the request. If all goes well the response will be an XML block, such as the one shown here.

  public function __construct($user, $key) 
  {
    $feed = curl_init(sprintf($this->apiurl, $user, $key));
    curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($feed, CURLOPT_HEADER, 0);
    $xml = curl_exec($feed);
    curl_close($feed);

Once the XML is loaded its time to parse it. This is made simple in PHP by use of SimpleXMLElement. It basically takes an XML string and returns an Object of elements. These elements can then be sifted through using something like a for..each loop, so we'll do just that.

    $result = new SimpleXMLElement($xml);

    $this->user = $result->recenttracks->attributes()->user;

    foreach($result->recenttracks->track as $track)
    {
        $song = new stdClass();
        $song->artist = (string) $track->artist;
        $song->name = (string) $track->name;
        $song->album = (string) $track->album;
        $song->url = (string) $track->url;
    
        array_push($this->songs, $song);
    }
    unset($feed, $xml, $result, $song);
  }

Once the for..each is completed the last part of the PHP class is to create a method that will return the song data.

    public function getSongs() { return $this->songs; }

Thats the whole script for working with the Last.fm API, simple, isn't it? That is the magic of a well crafted API. Now you just need to parse this newly fetched data and display it.

Once again, here is the completed script for easy copying and pasting.

<?php

class LFM_RecentlyPlayed
{
  public $songs = array();

  public $user = "";
  public $apiurl = "http://ws.audioscrobbler.com/2.0/"
	. "?method=user.getrecenttracks&user=%s&api_key=%s&limit=4";

  public function __construct($user, $key) 
  {
    $feed = curl_init(sprintf($this->apiurl, $user, $key));
    curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($feed, CURLOPT_HEADER, 0);
    $xml = curl_exec($feed);
    curl_close($feed);

    $result = new SimpleXMLElement($xml);

	$this->user = $result->recenttracks->attributes()->user;

    foreach($result->recenttracks->track as $track)
    {
        $song = new stdClass();
        $song->artist = (string) $track->artist;
        $song->name = (string) $track->name;
        $song->album = (string) $track->album;
        $song->url = (string) $track->url;

        array_push($this->songs, $song);
    }
    unset($feed, $xml, $result, $song);
  }
  public function getSongs() { return $this->songs; }
}

The limits of how you display this last played data is of course up to you, but here is one example.

<style type="text/css">

html, body {
	font: 14px Georgia, Verdana, Arial, Sans-Serif;
	color: #666666;
}

a:link,
a:active,
a:visited { 
	text-decoration: underline; 
	color: #666666;
}
a:hover { 
	text-decoration: none;
	background-color: #eeeeee;
	border-bottom: 1px solid #000000;
	color: #195c7e; 
}

.lfm_track {
	width: 500px;
	padding: 10px;
	border: 1px solid #cccccc;
	background-color: #eeeeee;
	margin-bottom: 5px;
}

.lfm_artist {
	font-weight: bold;
}

</style>

<h2>Last 5 Tracks Played from Last.fm</h2>

<?php

$lfm = new LFM_RecentlyPlayed("USERNAME_GOES_HERE", "API_KEY_GOES_HERE");
$tracks = $lfm->getSongs();

foreach($tracks as $track) 
{
	?>
	
	<div class="lfm_track">
		<span class="lfm_artist"><?=$track->artist;?></span><br />
		<span class="lfm_song"><a href="<?=$track->url;?>"><?=$track->name;?></a></span>
	</div>
	
	<?
}

?>

<small>Data from Last.fm user
<a href="http://www.last.fm/user/<?=$lfm->user?>"><strong><?=$lfm->user?></strong></a>

All done, you can now display the Last 5 songs you played, as long as Last.fm is logging it. This is of course only one of many useful abilities contained in the Last.fm API. I recommend you dig into the documentation and start playing around with the other calls you can make.

If you have comments or questions simply leave a message below. Hope you enjoyed this tutorial

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Display Last 5 Songs Played On Last.fm Using PHP

 Jerry  Sat Feb 4, 2012 3:07 am  
Hi, i get a error on line 9... Im not that into the php so sorry.. Can you help me out with this?
 mkeefe  Sat Feb 4, 2012 4:35 pm  
@Jerry - What error are you receiving?
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles