Last.fm Info with PHP


Update for 15 June 2006: Frederik M.J. Vestre has reworked my code to be able to use the XML feeds from last.fm. Kudos to him! If you want to give it a try, check out his Audioscrobbler XML data mining page. (as noted below, this page has changed location to the currently-linked folk.ntnu.no domain — 08 August 2007)

Update for 29 October 2005: I’ve modified things to no longer use cURL, so this should work for a wider range of users. I’ve also added the ability to display any of audioscrobbler’s text-based lists, including top albums and top artists. You can also put text before and after each list entry, which will allow you to turn these lists into proper HTML lists. Comments are welcome below. :)

If you have a last.fm account, you can use this PHP code to display your most recently-played songs on any webpage. Just download the last.fm info PHP file, rename it to “lastfm_info.php” (without the quotes), and stick it in the directory on your webserver that has the file you want your songs displayed on. WordPress users, put it in the same directory as your wp-config.php file.

Once you’ve got that done, add the following line to the file that you want your songs displayed in:
<?php include('lastfm_info.php'); ?>

Then, in that same file, put the following line where you want your songs displayed:
<?php display_lastfm_info( username, number_of_items, list, prefix, suffix, stats ); ?>

The only mandatory argument is your username. The other arguments are:

  1. number_of_items – the number of items you wish to be displayed, up to a maximum of ten. If you do not define this, then five items will be displayed.
  2. list – which list of items to display. This can be “topartists” (displays your Top Artists list), “topalbums” (displays your Top Albums list), “toptracks” (displays your Top Tracks list), “tags” (displays the tags you use most often to tag songs), “friends” (displays your friends), “neighbours” (displays your neighbours), or “recenttracks” (displays the tracks you recently listened to). If you do not define this, then your recent tracks will be displayed. This argument is case-insensitive.
  3. prefix & suffix – strings to display before and after each item. This can be used to present your list as an HTML list by setting prefix to <li> and suffix to </li>. If these are not defined, then nothing will be pre- or appended.
  4. stats – whether or not to display stats along with each item, where applicable. This applies to the “topartists”, “topalbums”, “toptracks”, and “tags”, by appending the number of each item after the item, in parentheses. For the “neighbours” list, it appends the percentage of commonality that you share with that neighbour. For example, if I have listened to Underworld 183 times, then with “stats” set to 1, this function will print “Underworld (183)”. If you wish stats to be displayed, set this to 1. If you do not define anything, then no stats will be displayed.

So, for basic functionality, if you just want to display your five most-recently played songs, you would call the function as:
display_lastfm_info( ’CanSpice’ );

If you want to display your ten most-listened to artists in an HTML list, with the number of listens after each artist, you would call the function as:
display_lastfm_info( ’CanSpice’, 10, ’topartists’, ’<li>’, ’</li>’, 1 );

Notes:

  1. The directory containing this code must be writable by the user under which the webserver runs. For example, on UNIX-based computers, this is typically the nobody user. You could set the directory to be owned by the nobody group, then set group write privileges by doing chmod g+w <dir> in a shell or over FTP. If you have difficulties doing this, please contact your hosting provider.
  2. This code caches the results from last.fm in order to comply with their requirements that the webservices not be accessed more than once every second for a given user. It downloads the results to a local file, and only requests an update from last.fm if that file is more than 30 seconds old.
  3. This code uses the plaintext file made available on audioscrobbler. Future plans include using the XML file for better artist and track name differentiation, along with linking back to last.fm automatically.
  4. The single quotes surrounding the various parameters are right single quotes, which are generated by (on standard North American English keyboards) the key just to the right of the Enter key. They’re not backticks.

This software is licensed under the GNU GPL, and is Copyright © 2005 Brad Cavanagh. All Rights Reserved.

  1. #1 by Chapree Da Grande on 09 February 2006 - 4:49 am

    Hi Brad,
    Thanks for making this cool stuff available for everyone! It does take me some time tweaking here and there to make it work but it’s working now (thanks to Geof too for his input!). Awesome stuff, you guys rock! \m/

  2. #2 by 3stripe on 15 February 2006 - 1:51 am

    Hey, got it working on my own :-)

    http://www.3stripe.net/

    Thanks again for this.

  3. #3 by Patch on 15 February 2006 - 11:54 am

    Got it workin’ on ExpressionEngine with a little experimentation. I had to place a blank as_recenttracks.txt (replace with whatever list you’re trying to download)in the root folder of the domain (where path.php is) and change its permission to 666. Works like a charm. Thanks for the script.

  4. #4 by Shin on 15 February 2006 - 7:07 pm

    Hey there Vrad, nice code, is there anyway to edit the layout of this? Instead of it being linear?

  5. #5 by Brad on 16 February 2006 - 9:55 am

    Linear? I’m not sure what you mean.

    You can change the tags that appear before and after each item in the list, if you want. You could surround them by div tags, for example, to put any kind of markup you want on them. This would be for the prefix and suffix options.

  6. #6 by Phil von Sassen on 17 February 2006 - 6:12 am

    Thank you very much. It works now on : sassen.org

  7. #7 by Phil von Sassen on 17 February 2006 - 6:55 am

    Is there a way to force the length of the string ?

  8. #8 by Brad on 17 February 2006 - 2:07 pm

    What do you mean by “length of the string”? Which string?

  9. #9 by George on 11 March 2006 - 8:31 pm

    Copied last_fm_info.php to my root folder.
    Added in index.php
    Added display_lastfm_info( ’username’, 10, ’topartists’, ’’, ’’, 1 );

    Getting :

    Warning: main(’lastfm_infophp’): failed to open stream: No such file or directory in /home/sleepwor/public_html/index.php on line 88

    Warning: main(’lastfm_infophp’): failed to open stream: No such file or directory in /home/sleepwor/public_html/index.php on line 88

    Warning: main(): Failed opening ‘’lastfm_infophp’’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/sleepwor/public_html/index.php on line 88

  10. #10 by Cosine2 on 11 March 2006 - 11:38 pm

    When I put the code into my sidebar.php file the entire sidebar disappears from my site.

  11. #11 by Brad on 13 March 2006 - 1:55 pm

    George: It looks like you’ve misspelled the “include” line. Make sure that the file you’re including is “lastfm_info.php”, not “lastfm_infophp”. Note the period between “info” and “php”.

    Cosine2: It could be that you’ve forgotten to close your PHP tags. Make sure you’ve done so.

  12. #12 by ANTONIOS on 15 March 2006 - 11:19 pm

    CAN YOU USE THIS CODE ON MYSPACE ???

  13. #13 by Brad on 16 March 2006 - 6:39 am

    ANTONIOS: If MySpace runs PHP, then yes. Otherwise, no.

  14. #14 by Alec on 17 March 2006 - 6:50 am

    Hey there,
    thanks for the neat script, i was getting tired of using predefined gif – images. I let it display my recent tracks. Is there a chance to have artists styled seperately? I want them bold, but just the singer, not the song.. :-)

  15. #15 by ady on 06 April 2006 - 6:52 pm

    Here’s another question… how do I get the script to display unusual characters – like certain letters in foreign songs?

  16. #16 by T.D! on 20 April 2006 - 2:44 am

    Ady: I’ve got the same problem, it won’t display the german Ü in Rammstein’s song “Küss mich”. But I think it has something to do with the encoding of your site. If you run iso-8859-1, try UTF-8 instead.

  17. #17 by Brad on 29 April 2006 - 6:55 pm

    Alec: I could have sworn that I coded up something that would let you get what you’ve requested, but I can’t find it! I think I must’ve written that code before I had a massive hard drive failure, and it got lost in a backup shuffle. Argh.

  18. #18 by Matthew on 05 May 2006 - 3:32 am

    hello there,

    could you give me some tips on getting this cool little script to display my weekly top artists as opposed to my overall top artists?

  19. #19 by Brad on 05 May 2006 - 9:10 am

    Matthew:

    This code only supports the text-based feeds. Unfortunately last.fm does not supply the weekly top artists in a text-based feed, only an XML feed.

    If last.fm were to supply the weekly top artists in a text-based feed, then this code would work. I suggest posting on last.fm’s forums, asking them to supply this feed.

  20. #20 by Matthew on 08 May 2006 - 1:14 am

    ok thanks

  21. #21 by Dirk on 22 July 2006 - 10:05 pm

    Brad.
    Firstly great code, I wasn’t looking forward to having to write something like this by myself.

    I was having a problem though, for some reason \n wasn’t creating a new line after each band name entry. I replaced it with a as I would in any normal html, and the problem was fixed.

    The thing is I can’t seem to find and reason why it wasn’t doing this in the first place, and thought maybe you would like to know.

    Once again, great code, thankyou.

  22. #22 by Chris on 09 October 2006 - 6:48 am

    Has anyone have an up-date of this script?As it no longer works ;(

    Cheers
    Chris

  23. #23 by Brad on 09 October 2006 - 9:00 am

    Chris: It still works, as you can see on my front page. If you tell me how it doesn’t work for you, including error messages, then I can help you get it working.

  24. #24 by Simon on 21 October 2006 - 3:07 am

    I’d love to add this to my website, but I’m wondering if making the directory world-writable is a security risk. Doesn’t this mean anyone can create and delete files there?

    Thanks,
    Simon

  25. #25 by Brad on 21 October 2006 - 7:59 am

    It is, yes. However, if you’re running a WordPress website, you’ve already done this to other directories in your webspace.

  26. #26 by Mikael on 15 December 2006 - 7:30 am

    Great script! But on my page the artist and title is presented as: Firefox AK – City To City bu i woult like it to look like: Firefox AK – City To City. Is it possible?

  27. #27 by Mikael (again) on 18 December 2006 - 9:45 am

    Solved my problem above!

  28. #28 by Five on 25 December 2006 - 6:54 pm

    Ok not sure if I will get any response anymore but I’ve been trying to find a cript to get my most recent tracks played listed on my site. But this is the only one that so far has given me anything back even if it is just errors. Anyway the errors are:

    fopen(): URL file-access is disabled in the server configuration in /usr/home/admin/public_html/five/scripts/lastfm_info.php on line 84
    fopen(http://ws.audioscrobbler.com/1.0/user/fivesevennine/recenttracks.txt): failed to open stream: no suitable wrapper could be found in /usr/home/admin/public_html/five/scripts/lastfm_info.php on line 84

    I set the folders CHMOD to 777 (using an FTP program) is that enough or do I need to do something more?

  29. #29 by Five on 25 December 2006 - 7:10 pm

    Nevermind I got it to work. Had to use the function that used the CURL lib instead.

    Basically if you are getting this error, comment the fopen code block (put the code inbetween /* {CODE} */) and remove the other /* */ in the code.

  30. #30 by Five on 25 December 2006 - 8:08 pm

    Ok wow 3 consecutive posts in less than an hour, sorry. But I have the same problem as Mikael did, where the – apears instead of the -. So how do you fix this?

    I inserted:
    $cache = str_replace( ‘–’, ‘-’, $cache );
    into multiple places in the code and still no change, I also used $cachefile instead of $cache, but still not working. Thanks for any help, and sorry about the 3 posts =/.

  31. #31 by Mikael on 05 January 2007 - 8:18 am

    Solved my problem by adding into my page, and after that it works fine.

  32. #32 by Mikael on 05 January 2007 - 8:18 am

    meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″

  33. #33 by Mauvis on 13 February 2007 - 7:59 pm

    I’m in the same boat as a few people, my host doesn’t allow me access to fopen. I tried the comment about from Five but still no luck. Perhaps I’m commenting out the wrong part. If anyone can post the code for the full libcurl version that would be great. Thanks.

  34. #34 by chris on 22 February 2007 - 12:26 pm

    i’ve fudged with this for a while now and all i get is a blank page. if i view source i see the html code. i’ve tried making the page i load a .hml file and a .php file. i’ve messed with permissions on my server even granting everyone r/w/x just to see if it worked… it didn’t.

    test

    ‘ ); ?>

    any ideas? thanks!
    would love to get this working

  35. #35 by chris on 22 February 2007 - 12:27 pm

    [CODE]

    test

    [/CODE]

  36. #36 by chris on 22 February 2007 - 12:28 pm

    trying to get my html to show up. sorry. you can delete that last post… and this one. :)

  37. #37 by FreqMod on 08 August 2007 - 1:01 am

  38. #38 by Aaron on 24 February 2010 - 8:25 am

    If you want the script to display in more of a sentence, like ‘My favourite artists are Band 1, Band 2 and Band 3.’, then edit lines 124-127 which was:

    [code]
    case "toptracks":
    $pieces = explode( ",", fgets( $fp, 4096 ), 3 );
    if( $displaystats ) {
    echo $prefix . rtrim( $pieces[2] ) . " (" . $pieces[1] . ")" . $suffix . "\n";
    } else {
    echo $prefix . rtrim( $pieces[2] ) . $suffix . "\n";
    }
    break;[/code]

    Into

    [code]
    case "toptracks":
    $pieces = explode( ",", fgets( $fp, 4096 ), 3 );
    if( $displaystats ) {

    if($linenumber == $max)
    echo "and " . $prefix . rtrim( $pieces[2] ) . " (" . $pieces[1] . ")" . $suffix . "\n";

    elseif($linenumber == ($max-1))
    echo $prefix . rtrim( $pieces[2] ) . " (" . $pieces[1] . ")" . $suffix . " \n";

    else
    echo $prefix . rtrim( $pieces[2] ) . " (" . $pieces[1] . ")" . $suffix . ", \n";

    } else {

    if($linenumber == $max)
    echo "and " . $prefix . rtrim( $pieces[2] ) . $suffix . "\n";

    elseif($linenumber == ($max-1))
    echo $prefix . rtrim( $pieces[2] ) . $suffix . " \n";

    else
    echo $prefix . rtrim( $pieces[2] ) . $suffix . ", \n";
    }
    break;[/code]

    Therefor this:

    [code] My top artists are .[/code]

    Would display:

    My top artists are Band 1, Band 2, Band 3 and Band 4.

    Hope that helps :)

  39. #39 by Aaron on 24 February 2010 - 8:26 am

    *Looks like [code][/code] doesn’t work, hope the code still makes sence. You can see a working preview at http://aerialdesign.co.uk/authors, where it talks a bit about the authors of the site, then the most recent tracks displayed like the above code.

  40. #40 by Rosa on 22 March 2010 - 9:38 pm

    Any way to display recently “Loved” tracks?

  41. #41 by Justin on 05 August 2010 - 4:10 pm

    Excellent!

    Was looking for this, saw that it was last updated in 2006, BUT it still works!

    Thanks.

  42. #42 by Justin on 08 August 2010 - 10:12 pm

    Did you ever figure this out?

    Rosa :

    Any way to display recently “Loved” tracks?

(will not be published)