* @link http://iamkoa.net * @license http://www.opensource.org/licenses/bsd-license.php * @uses SimpleXML */ class LastFm { /** * LastFm API URL * @var string */ public $base_url = "http://ws.audioscrobbler.com/2.0/"; /** * LastFm auth URL * @var string */ public $auth_url = "http://www.last.fm/api/auth/"; /** * LastFm API key * @var string */ public $key = null; /** * Magic function used to make API call * * @param string $method LastFm API method * @param string $args LastFm API args * @return obj XML data converted to a PHP object * @uses SimpleXML * ex: * $lastfm->user_getLovedTracks("user=iamkoa"); * Calls API method "user.getLovedTracks" and sets * the "user" argument to "iamkoa". */ private function __call ($method, $args) { $this->url = $this->buildCall($method, $args); $this->xml = $this->makeCall($this->url); return simplexml_load_string($this->xml); } /** * Gets the API key * * @param string $glue The character that precedes the API key * @return string Formatted API key */ private function getKey ($glue = null) { if (is_null($this->key)) return false; return $glue."api_key=".$this->key; } /** * Gets the API call * * @param string $method LastFm API method - append with "auth_" to require authentication * @return string Formatted API method */ private function getMethod ($method) { $ex = explode("_",$method); if ($ex[0] == 'auth') { /* we've requested authentication */ // build auth url $url = $this->auth_url.$this->getKey("?"); // make call exit(print_r($this->makeCall($url))); $method = $ex[1].".".$ex[2]; } else $method = str_replace('_','.',$method); $this->method = "?method="; $this->method .= $method; $this->method .= '&'; return $this->method; } /** * Gets the API arguments * * @param string $method LastFm API args * @return string Formatted API args */ private function getArgs ($args) { if (is_array($args)) { $this->args = implode('&',$args); return $this->args; } } /** * Builds the API call * * @param string $method LastFm API args * @param string $args LastFm API args * @return string Formatted API args * @see getArgs() */ private function buildCall ($method, $args) { $this->call_url = $this->base_url; $this->call_url .= $this->getMethod($method); $this->call_url .= $this->getArgs($args); $this->call_url .= $this->getKey("&"); return $this->call_url; } /** * Call the API * * @param string $url LastFm API url call * @return xml Formatted API results * @see buildCall() */ private function makeCall ($url) { $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 8); $this->results = curl_exec($ch); curl_close($ch); return $this->results; } }