Last.fm to Spotify Play

Spotify recently announced their new Play Button. So I thought it'd be cool to incorporate it into my homepage. But what tracks should I have be played? Then I got the idea of using my Last.fm charts to generate the tracklist.

So first I had to grab my weekly track chart from Last.fm, thankfully they provide a nice xml feed which can be found at ws.audioscrobbler.com/2.0/user/[username]/weeklytrackchart.xml. I just used the cURL extension in PHP to grab the XML and the parsed it to grab the track names and artist names and store them temporarily in an array.

Now, for getting the Spotify track IDs so I can generate the play button. Thankfully Spotify has an open MetaData API that I can use to search for and retrieve the IDs. I took great influence from this PHP library called metatune. However, it does far more than I need, and it uses file_get_contents to query the API, which requires having allow_url_fopen set to true in my php.ini file. I'd rather use cURL, its faster and more versatile.

There is one caveat, searching Spotify normally leads to multiple results. I've assumed that the first track is the one I want. I then get this list of track IDs and save them to file. Its then just a question of reading this list and dumping it into the HTML of the homepage.

You can have a look at my code on GitHub, its not quite finished, I need to incorporate some sort of actual error handling.