Mirror last.fm listening statistics

·

A tiny PHP script that you can run regularly with cron (every 30 minutes or so should be enough, as the feed contains the last 10 items): it will fetch the specified user's recently logged tracks from last.fm and insert them into a MySQL table.

Edit the appropriate database details and username before use.


<?php
$lastfm_user = 'USERNAME';
mysql_connect('localhost', 'DB_USER', 'DB_PASS');
mysql_select_db('DB_NAME');
mysql_query('CREATE TABLE IF NOT EXISTS `tracks` (`artist_mbid` varchar(32) default NULL,  `artist_name` varchar(255) default NULL,  `track_mbid` varchar(32) default NULL,  `track_name` varchar(255) default NULL,  `url` varchar(255) default NULL,  `date` int(11) NOT NULL,  UNIQUE KEY `track_date` (`track_name`,`date`),  KEY `date` (`date`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;');
$xml = simplexml_load_file("http://ws.audioscrobbler.com/1.0/user/$lastfm_user/recenttracks.xml");
foreach ($xml->track as $track) mysql_query(sprintf(
    "INSERT IGNORE INTO tracks (`artist_mbid`, `artist_name`, `track_mbid`, `track_name`, `url`, `date`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
    mysql_real_escape_string($track->artist['mbid']),
    mysql_real_escape_string($track->artist),
    mysql_real_escape_string($track->mbid),
    mysql_real_escape_string($track->name),
    mysql_real_escape_string($track->url),
    mysql_real_escape_string($track->date['uts'])));
mysql_close();
?>