Skip to content

Instantly share code, notes, and snippets.

@ivuorinen
Created November 26, 2010 09:35
Show Gist options
  • Save ivuorinen/716465 to your computer and use it in GitHub Desktop.
Save ivuorinen/716465 to your computer and use it in GitHub Desktop.
PHP5 function to get recent plays from last.fm and caching the results for about of time.
<?php
require_once("tunar.php");
$tunar = tunar( "drifter9000" );
?><pre><?php print_r( $tunar ); ?></pre>
<?php
header('content-type: text/html; charset: utf-8');
/**
* PHP5 function to get recent plays from last.fm
* and caching the results for about of time.
*
* @author Ismo Vuorinen ivuorinen@gmail.com
* @version $Id$
* @copyright Hollow13.net, 9 May, 2008
* @package Hollow13
**/
/**
* tunar, the function that does the heavy lifting
*
* @param string $username your last.fm username
* @return array
* @author Ismo Vuorinen ivuorinen@gmail.com
*
* <code>
* $plays = tunar( "drifter9000" );
* $np = $plays[0];
* echo "like ". $np[0] ." seconds ago I was listening to ". $np[2] ." from this band called ".$np[1];
* </code>
*
*/
function tunar( $username = "drifter9000" ) {
/**
* Cache dir. To support many users use {$username} at some point of the filename.
*/
$cache = "./cache/lastfm-{$username}.cache";
/**
* Let's check is the folder for cache writable.
*/
if( !is_writable( dirname($cache) ) ) {
die("This \"". dirname($cache) ."\" folder isn't writable. Please chmod it to 777.");
}
/**
* Let's cache the data for 5 minutes.
*/
if( file_exists( $cache ) && filemtime( $cache ) > 300 || !file_exists( $cache ) ) {
$get_data = @file("http://ws.audioscrobbler.com/1.0/user/". $username ."/recenttracks.xml");
file_put_contents( $cache, $get_data ); // Save the data to cache.
if( filesize($cache) < 1 ) { die("Something went wrong. Check the batteries."); }
}
/**
* Now we can safely load the everfresh data.
*/
$data = file( $cache ); // Let's load the data
if( isset( $data ) && count( $data ) > 0 ) {
foreach ($data as $id => $v) {
$x = explode(",", $v); // Explode the time and info
$t = $x[0]; // Time
$n = utf8_decode( $x[1] ); // Artist and track
#$n = iconv( $i, iconv_get_encoding( $x[1] ), $x[1]); // $n is now utf-8 encoded "artist - track"
$n = explode(" - ", $n);
$art = $n[0];
$tit = $n[1];
$np[$id] = array(
"x" => $t, // Time
"a" => $art, // Artist
"t" => $tit // Song title
);
}
}
return $np;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment