Skip to content

Instantly share code, notes, and snippets.

@florianeckerstorfer
Created June 21, 2010 21:55
Show Gist options
  • Save florianeckerstorfer/447565 to your computer and use it in GitHub Desktop.
Save florianeckerstorfer/447565 to your computer and use it in GitHub Desktop.
<?php
namespace com\florianeckerstorfer\LastFm;
/**
* @package com.florianeckerstorfer.lastfm
* @author Florian Eckerstorfer <[email protected]>
* @link http://florianeckerstorfer.com Florian Eckerstorfer
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3
* @copyright 2010 Florian Eckerstorfer
*/
class LastFm
{
/** @var string */
protected $apiKey;
/** @var string */
protected $baseUrl = 'http://ws.audioscrobbler.com/2.0/';
/**
* @param string $apiKey last.fm API key.
*/
public function __construct($apiKey)
{
$this->apiKey = $apiKey;;
}
/**
* @param string $username
* @param string $limit
* @param string $page
* @return array
*/
public function getRecentTracks($username, $limit = 10, $page = 1)
{
$xml = $this->execute(array(
'method' => 'user.getrecenttracks',
'user' => $username,
'limit' => $limit,
'page' => $page
));
$tracks = array();
foreach ($xml->recenttracks->track as $track)
{
$tracks[] = array(
'artist' => strval($track->artist),
'name' => strval($track->name),
);
}
return $tracks;
}
public function getWeeklyChartList($username)
{
$xml = $this->execute(array(
'method' => 'user.getweeklychartlist',
'user' => $username,
));
$charts = array();
foreach ($xml->weeklychartlist->chart as $chart)
{
$charts[] = array(
'from' => strval($chart['from']),
'to' => strval($chart['to']),
);
}
return $charts;
}
public function getWeeklyArtistChart($username, $from = null, $to = null)
{
$xml = $this->execute(array(
'method' => 'user.getweeklyartistchart',
'user' => $username,
'from' => $from,
'to' => $to,
));
$artists = array();
foreach ($xml->weeklyartistchart->artist as $artist)
{
$artists[] = array(
'name' => strval($artist->name),
'playcount' => strval($artist->playcount),
'url' => strval($artist->url),
);
}
return $artists;
}
/**
* Executes a last.fm API call using cURL.
*
* @param array $parameters
* @return SimpleXMLElement
*/
protected function execute(array $parameters)
{
$parameters['api_key'] = $this->apiKey;
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $this->baseUrl . '?' . http_build_query($parameters));
$response = curl_exec($curl);
curl_close($curl);
if (!$response)
{
throw new \Exception('Could not execute last.fm API call.');
}
return simplexml_load_string($response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment