ФАЙЛ staus.xsl

  • Автор темы Автор темы maxon
  • Дата начала Дата начала

maxon

New member
Как подключится к айкасту для получения данных что спарсить staus.xsl
 
maxon сказал(а):
Как подключится к айкасту для получения данных что спарсить staus.xsl
Вообще Радиобосс сам парсит статистику. А если Вам надо еще вытянуть например имя трека то его можно посылать РБ на сервер и там читать.
В этой теме есть примеры https://www.radioboss.ru/smf_ru/index.php/topic,995.msg4475.html#msg4475

А еще много знает об этом товарищ Гугль - https://www.google.com.ua/search?q=%D0%BF%D0%B0%D1%80%D1%81%D0%B8%D1%82%D1%8C+status.xsl+icecast
 
Добрый день.

А если мне надо не с радиобосса парсить а с вашего радиохостинга когда играет nonstop.

Пытаюсь спарсить staus.xsl таким методом

function getStreamInfo(){
$str = @file_get_contents(SERVER.'/status.xsl?mount='.MOUNT);
if(preg_match_all('/<td\s[^>]*class=\"streamdata\">(.*)<\/td>/isU', $str, $match)){
$stream['info']['status'] = 'ON AIR';
$stream['info']['title'] = $match[1][0];
$stream['info']['description'] = $match[1][1];
$stream['info']['type'] = $match[1][2];
$stream['info']['start'] = $match[1][3];
$stream['info']['bitrate'] = $match[1][4];
$stream['info']['listeners'] = $match[1][5];
$stream['info']['msx_listeners'] = $match[1][6];
$stream['info']['genre'] = $match[1][7];
$stream['info']['stream_url'] = $match[1][8];
$stream['info']['artist_song'] = $match[1][9];
$x = explode(" - ",$match[1][9]);
$stream['info']['artist'] = $x[0];
$stream['info']['song'] = $x[1];
}
else{
$stream['info']['status'] = 'OFF AIR';
}
return $stream;
}

Но я не могу http://xxx.radioboss.fm:8000  - Это в качестве сервера SERVER
Точка мантирования MOUNT - название станции

Как можно спарсить staus.xsl  ?

т.е.  http://xxx.radioboss.fm:8000/status.xsl?MOUNT  не парсит так.
 
XNTPbIY сказал(а):
А если мне надо не с радиобосса парсить а с вашего радиохостинга когда играет nonstop.

Тогда проще всего парсить .xspf файл.

Приблизительный код  (как у меня)



function stream_check($file_check) {
$Headers = @get_headers($file_check);
if (!preg_match("|200|", $Headers[0])) return '';
else return $file_check;
}


$ip = "xxx.radioboss.fm";
$port = 8000;




function get_web_page( $url )
{
  $uagent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0";

  $ch = curl_init( $url );

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // возвращает веб-страницу
  curl_setopt($ch, CURLOPT_HEADER, 0);          // не возвращает заголовки
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);  // переходит по редиректам
  curl_setopt($ch, CURLOPT_ENCODING, "");        // обрабатывает все кодировки
  curl_setopt($ch, CURLOPT_USERAGENT, $uagent);  // useragent
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // таймаут соединения
  curl_setopt($ch, CURLOPT_TIMEOUT, 120);        // таймаут ответа
  curl_setopt($ch, CURLOPT_MAXREDIRS, 10);      // останавливаться после 10-ого редиректа

  $content = curl_exec( $ch );
  $err    = curl_errno( $ch );
  $errmsg  = curl_error( $ch );
  $header  = curl_getinfo( $ch );
  curl_close( $ch );

  $header['errno']  = $err;
  $header['errmsg']  = $errmsg;
  $header['content'] = $content;
  return $header;
}

function check_mode($i){
global $ip,$port,$xmlf;
        $i = $i ? $i : 0;
        if($i>=0 AND $i<=9) { $ip = $ip; $port = $port; }

        $potok = stream_check('http://xxx.radioboss.fm:8000/MOUNT.xspf');

$result = get_web_page($potok);

if ($result['http_code'] == 200 && $result['size_download'] > 400) return $potok;
else return false;
}

$potok = check_mode(1) ?: (check_mode(0) ?: "Нет потока".$result['errmsg']);


        if($potok) {
        $xml = @simplexml_load_file($potok);

        //обращение к xspf файлу текущего потока
        $ano = $xml->trackList->track->annotation;
        //выбираем значение из <trackList><track><annotation>
$ano = iconv("utf-8","windows-1251",$ano);
       
        $mass = explode("\n", $ano);
        $station = substr($mass[1],20);
 
        $title = $xml->trackList->track->title;
        $title = str_replace("_"," ",$title);
        $title = iconv("utf-8","windows-1251",$title);
        //выбираем значение из <trackList><track><title>

    echo '<div style="color: #f50;line-height: 18px;font-size: 10px;font-family:Arial;text-align: left;">';
    echo 'В эфире: <span style="color: #ccc;">'.$title.'</span>';
    echo '</div>';

        } else echo "Нет потока";

    //выводим полученные значения


Аналогично там можно вытянуть остальные данные. Кодировку меняйте на свою и при необходимости функции кодирования можно убрать.
 
scorp сказал(а):
Тогда проще всего парсить .xspf файл.

Приблизительный код  (как у меня)

Ваш код работает безусловно. Задача у меня была с парсить название трека артиста и  вывести обложку c lastfm для этого использовал такой код.

Код:
libxml_disable_entity_loader(false);

//Get data from config_now.php
require('config_now.php');
$stream = getStreamInfo();
if($stream['info']['status'] == 'OFF AIR'){
	cacheVar($stream);
}
else{
	$last_song = @file_get_contents('last.txt');
	if($last_song != base64_encode($stream['info']['song'])){
		$stream = init($stream);
		$stream = getInfo($stream);
		file_put_contents('last.txt', base64_encode($stream['info']['song']));
		cacheVar($stream);
	}
	else{
		$stream = array_decode(json_decode(@file_get_contents('var/info.json'), TRUE));
	}
}


function obj_to_array($obj){
	$array = (is_object) ? (array)$obj : $obj;
	foreach($array as $k=>$v){
		if(is_object($v) OR is_array($v))
			$array[$k] = obj_to_array($v);
	}
	return $array;
}

//Get and read the stream info
function getStreamInfo(){
	$str = @file_get_contents(SERVER.'/status.xsl?mount='.MOUNT);
	if(preg_match_all('/<td\s[^>]*class=\"streamdata\">(.*)<\/td>/isU', $str, $match)){
		$stream['info']['status'] = 'ON AIR';
		$stream['info']['title'] = $match[1][0]; 
		$stream['info']['description'] = $match[1][1]; 
		$stream['info']['type'] = $match[1][2]; 
		$stream['info']['start'] = $match[1][3]; 
		$stream['info']['bitrate'] = $match[1][4]; 
		$stream['info']['listeners'] = $match[1][5]; 
		$stream['info']['msx_listeners'] = $match[1][6]; 
		$stream['info']['genre'] = $match[1][7]; 
		$stream['info']['stream_url'] = $match[1][8];
		$stream['info']['artist_song'] = $match[1][9];
			$x = explode(" - ",$match[1][9]); 
		$stream['info']['artist'] = $x[0]; 
		$stream['info']['song'] = $x[1];
	}
	else{
		$stream['info']['status'] = 'OFF AIR';
	}
	return $stream;
}


//Get information of the current song
function getTrackInfo($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=track.getinfo&artist='.urlencode($stream['info']['artist']).'&track='.urlencode($stream['info']['song']).'&api_key='.LAST_FM_API);
	$url = str_replace('%20','+',$url);
	
	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);
	
	//Get the cover of the song (you can choose the quality of the cover)
	if(isset($xml['track']['album']['image'])){
		$stream['album']['image_s'] = $xml['track']['album']['image'][0];
		$stream['album']['image_m'] = $xml['track']['album']['image'][1];
		$stream['album']['image_l'] = $xml['track']['album']['image'][2];
		$stream['album']['image_xl'] = $xml['track']['album']['image'][3];
		
	} else {
		
		$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist='.urlencode($stream['info']['artist']).'&api_key='.LAST_FM_API.'&autocorrect=1');
		$url = str_replace('%20','+',$url);
		
		$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
		$xml = obj_to_array($xml);
		
		//Get the cover of the artist if it can't find the cover of the song		
		if(isset($xml['artist']['image'])){
			
			$stream['album']['image_s'] = $xml['artist']['image'][0];
			$stream['album']['image_m'] = $xml['artist']['image'][1];
			$stream['album']['image_l'] = $stream['album']['image_xl'] = $xml['artist']['image'][2];
					
		} else {
			//If nothing. show a default cover
			$stream['album']['image_s'] = $stream['album']['image_m'] = $stream['album']['image_l'] = $stream['album']['image_xl'] = DEFAULT_ALBUM_ART;
		}
		if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
		}
	}
	//Get the informatin of the song
	if(isset($xml['track']['wiki']['summary'])){
		$stream['track']['summary'] = $xml['track']['wiki']['summary'];
		$stream['track']['info'] = $xml['track']['wiki']['content'];
	}
	//Get the album title and URL of the current song
	if(isset($xml['track']['album']['title'])){
		$stream['album']['title'] = $xml['track']['album']['title'];
		$stream['album']['lastfm_url'] = $xml['track']['album']['url'];
	}
	$stream['track']['lastfm_url'] = $xml['track']['url'];
	if(isset($xml['track']['artist']['url'])){
		$stream['artist']['lastfm_url'] = $xml['track']['artist']['url'];
	} else {
		$stream['artist']['lastfm_url'] = 'http://www.google.com/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']);
	}
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
	return $stream;

}
	
//Get extra information of the album
function getAlbumInfo($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=album.getinfo&artist='.urlencode($stream['info']['artist']).'&album='.urlencode($stream['album']['title']).'&api_key='.LAST_FM_API);
	$url = str_replace('%20','+',$url);
	
	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);
	
	//Get the album release date
	if ($xml['album']['releasedate'] && strlen($xml['album']['releasedate']) > 10){
		$stream['album']['releasedate'] = reset(explode(",",$xml['album']['releasedate']));
	}
	
	//Get the album tracklisting
	if(isset($xml['album']['tracks']['track'])){
		foreach($xml['album']['tracks']['track'] as $track){
			$stream['album']['track_list'][] = array('title' => $track['name'],'url' => $track['url']);
		}
	}
	
	//Get the informatin of the current album
	if(isset($xml['album']['wiki']['summary'])){
		$stream['album']['summary'] = $xml['album']['wiki']['summary'];
		$stream['album']['info'] = $xml['album']['wiki']['content'];
	}
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
	return $stream;
}

//Get extra information of the artist		
function getArtistInfo($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist='.urlencode($stream['info']['artist']).'&api_key='.LAST_FM_API.'&autocorrect=1');
	$url = str_replace('%20','+',$url);

	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);		
	
	//Get the top albums of the artist
	//if(isset($xml['topalbums']['album'])){
	//	foreach($xml['topalbums']['album'] as $album){
	//		$stream['artist']['top_albums'][] = array('title'=>$album['name'], 'url'=>$album['url'], 'image'=>$album['image']);
	//	}
	//}
	
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist='.urlencode($stream['info']['artist']).'&api_key='.LAST_FM_API.'&autocorrect=1');
	$url = str_replace('%20','+',$url);

	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);
	
	//Get the cover of the artist
	if(isset($xml['artist']['image'])){
		$stream['artist']['image_s'] = $xml['artist']['image'][0];
		$stream['artist']['image_m'] = $xml['artist']['image'][1];
		$stream['artist']['image_l'] = $xml['artist']['image'][2];
	}	
	
	//Get the bio of the artist
	if(isset($xml['artist']['bio']['summary'])){
		$stream['artist']['summary'] = $xml['artist']['bio']['summary'];
		$stream['artist']['info'] = $xml['artist']['bio']['content'];
	}
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
	return $stream;
}

//get the buylink   
function getTrackBuyLink($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=track.getBuylinks&artist='.urlencode($stream['info']['artist']).'&track='.urlencode($stream['info']['song']).'&api_key='.LAST_FM_API.'&country='.urlencode('united states').'&autocorrect=1');
	$url = str_replace('%20','+',$url);

	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);	

        if(isset($xml['affiliations']['physicals']['affiliation'])){
                foreach($xml['affiliations']['physicals']['affiliation'] as $buy){
                        $supplier = str_replace('iTuens', 'iTunes', $buy['supplierName']);
                        if($buy['isSearch'] == 0){
                                $new = array('link' => $buy['buyLink'], 'price'=>$buy['price']['amount'], 'currency'=>$buy['price']['currency'], 'icon'=>$buy['supplierIcon']);
                        }
                        else{
                                $new = array('link' => $buy['buyLink'],'icon'=>$buy['supplierIcon']);
                        }
                        $stream['track']['buylink']['physical'][$supplier] = $new;
                }
        }
        if(isset($xml['affiliations']['downloads']['affiliation'])){
                foreach($xml['affiliations']['downloads']['affiliation'] as $buy){
                        $supplier = str_replace('Amazon MP3', 'Amazon', $buy['supplierName']);
                        if($buy['isSearch'] == 0){
                        
                        		//$new = array('link' => $buy['buyLink'], 'price'=>$buy['price']['amount'], 'currency'=>$buy['price']['currency'], 'icon'=>$buy['supplierIcon']);                       
                                $new = array('link' => $buy['buyLink'],'icon'=>$buy['supplierIcon']);
                                
                        }
                        else{
                                $new = array('link' => $buy['buyLink'],'icon'=>$buy['supplierIcon']);
                        }
                        $stream['track']['buylink']['download'][$supplier] = $new;
                }
        }
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
        return $stream;
}


		
//Get lyrics from chartlyrics.com's API
function getLyric($artist, $song){
	$url = str_replace('\'','','http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist='.urlencode($artist).'&song='.urlencode($song));
	$feed = @file_get_contents($url);
	$info = simplexml_load_string($feed);
	$xml = obj_to_array($info);

	if($xml['LyricId'] && ($xml['Lyric'] != array())){
		return $xml['Lyric'];
	}
	else{
		return 'Sorry, there\'s no lyric found for this song';
	}
}

function getInfo($stream){
	if(!$stream['info']['song']){
		$stream['info']['song'] == 'Not found';
		return $stream;
	}
	if(GET_TRACK_INFO == TRUE){
		$stream = getTrackInfo($stream);
	}
	if(GET_ALBUM_INFO && isset($stream['album']['title'])){
		$stream = getAlbumInfo($stream);
	}
	if(GET_ARTIST_INFO == TRUE){
		$stream = getArtistInfo($stream);
	}
	if(GET_TRACK_BUY_LINK == TRUE){
		$stream = getTrackBuyLink($stream);
	}
	if(GET_LYRICS == TRUE){
		$stream['track']['lyric'] = getLyric($stream['info']['artist'], $stream['info']['song']);
	}
	$stream['fetch_time'] = time();
	return $stream;
}

function array_encode($array){
	foreach($array as $key=>$value){
		if(is_array($value)){
			$array[$key] = array_encode($value);
		}
		else{
			$array[$key] = base64_encode($value);
		}
	}
	return $array;
}

function array_decode($array){
	foreach($array as $key=>$value){
		if(is_array($value)){
			$array[$key] = array_decode($value);
		}
		else{
			$array[$key] = base64_decode($value);
		}
	}
	return $array;
}

function cacheVar($stream){
	$stream = array_encode($stream);
	file_put_contents('var/info.json', json_encode($stream));
}

function init($stream){
	$stream['album']['image_s'] = $stream['album']['image_m'] = $stream['album']['image_l'] = $stream['album']['image_xl'] = DEFAULT_ALBUM_ART;
	$stream['track']['summary']  = $stream['track']['info'] = "No information found for this track, try searching for <a target='_blank' href='http://www.google.com/search?q=".urlencode($stream['info']['artist']." - ".$stream['info']['song'])."'>".$stream['info']['artist']." - ".$stream['info']['song']."</a> on Google";
	$stream['album']['title'] = 'Not found';
	$stream['album']['lastfm_url'] = 'http://www.google.com/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']);
	$stream['track']['download_cn'] = 'http://www.google.cn/music/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']);
	$stream['album']['summary'] = $stream['album']['info'] = 'No information found for this album, try searching for <a target="_blank" href="http://www.google.com/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']).'">'.$stream['info']['artist']." - ".$stream['info']['song'].'</a> on Google';
	$stream['album']['releasedate'] = 'Unknown';
	$stream['artist']['summary'] = $stream['artist']['info'] = 'No information found for this artist, try searching for <a target="_blank" href="http://www.google.com/search?q='.urlencode($stream['info']['artist']).'">'.$stream['info']['artist'].'</a> on Google';
	return $stream;
}

Планировался такой вывод , в вашем случаи идет тока вывод названия трека. Пытался объединить ваше со своим без успешно.
 
Вот код каторый я пытался адаптировать под свои нужды.

Еще config_now.php  там прописан ключ к lastfm и вкл и отключения сервисов покупки.

Код:
require('config_now.php');



function stream_check($file_check) {
$Headers = @get_headers($file_check);
if (!preg_match("|200|", $Headers[0])) return '';
else return $file_check;
}
 

$ip = "xxx.radioboss.fm";
$port = 8000;




function get_web_page( $url )
{
  $uagent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0";

  $ch = curl_init( $url );

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   // возвращает веб-страницу
  curl_setopt($ch, CURLOPT_HEADER, 0);           // не возвращает заголовки
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);   // переходит по редиректам
  curl_setopt($ch, CURLOPT_ENCODING, "");        // обрабатывает все кодировки
  curl_setopt($ch, CURLOPT_USERAGENT, $uagent);  // useragent
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // таймаут соединения
  curl_setopt($ch, CURLOPT_TIMEOUT, 120);        // таймаут ответа
  curl_setopt($ch, CURLOPT_MAXREDIRS, 10);       // останавливаться после 10-ого редиректа

  $content = curl_exec( $ch );
  $err     = curl_errno( $ch );
  $errmsg  = curl_error( $ch );
  $header  = curl_getinfo( $ch );
  curl_close( $ch );

  $header['errno']   = $err;
  $header['errmsg']  = $errmsg;
  $header['content'] = $content;
  return $header;
}

function check_mode($i){
global $ip,$port,$xmlf;
        $i = $i ? $i : 0;
        if($i>=0 AND $i<=9) { $ip = $ip; $port = $port; }

        $potok = stream_check('http://xxx.radioboss.fm:8000/autodj.xspf');

$result = get_web_page($potok);

if ($result['http_code'] == 200 && $result['size_download'] > 400) return $potok;   
else return false;
}

$potok = check_mode(1) ?:   (check_mode(0) ?: "Нет потока".$result['errmsg']);

   
        if($potok) {
        $xml = @simplexml_load_file($potok);

        //обращение к xspf файлу текущего потока
        $ano = $xml->trackList->track->annotation;
        //выбираем значение из <trackList><track><annotation>
            $ano = iconv("utf-8","windows-1251",$ano);
        
        $mass = explode("\n", $ano);
        $station = substr($mass[1],20);
   
        $stream = $xml->trackList->track->title;
        $stream = str_replace("_"," ",$stream);
        $stream = iconv("utf-8","windows-1251",$stream);
        //выбираем значение из <trackList><track><title>

    echo '<div style="color: #f50;line-height: 18px;font-size: 10px;font-family:Arial;text-align: left;">';
    echo 'В эфире: <span style="color: #ccc;">'.$stream.'</span>';
    echo '</div>';

        } else echo "Нет потока";
	

////////////////////////////////////////////////////////////////////////////////////////////////////////////////




	
//Get information of the current song
function getTrackInfo($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=track.getinfo&artist='.urlencode($stream['info']['artist']).'&track='.urlencode($stream['info']['song']).'&api_key='.LAST_FM_API);
	$url = str_replace('%20','+',$url);
	
	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);
	
	//Get the cover of the song (you can choose the quality of the cover)
	if(isset($xml['track']['album']['image'])){
		$stream['album']['image_s'] = $xml['track']['album']['image'][0];
		$stream['album']['image_m'] = $xml['track']['album']['image'][1];
		$stream['album']['image_l'] = $xml['track']['album']['image'][2];
		$stream['album']['image_xl'] = $xml['track']['album']['image'][3];
		
	} else {
		
		$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist='.urlencode($stream['info']['artist']).'&api_key='.LAST_FM_API.'&autocorrect=1');
		$url = str_replace('%20','+',$url);
		
		$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
		$xml = obj_to_array($xml);
		
		//Get the cover of the artist if it can't find the cover of the song		
		if(isset($xml['artist']['image'])){
			
			$stream['album']['image_s'] = $xml['artist']['image'][0];
			$stream['album']['image_m'] = $xml['artist']['image'][1];
			$stream['album']['image_l'] = $stream['album']['image_xl'] = $xml['artist']['image'][2];
					
		} else {
			//If nothing. show a default cover
			$stream['album']['image_s'] = $stream['album']['image_m'] = $stream['album']['image_l'] = $stream['album']['image_xl'] = DEFAULT_ALBUM_ART;
		}
		if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
		}
	}
	//Get the informatin of the song
	if(isset($xml['track']['wiki']['summary'])){
		$stream['track']['summary'] = $xml['track']['wiki']['summary'];
		$stream['track']['info'] = $xml['track']['wiki']['content'];
	}
	//Get the album title and URL of the current song
	if(isset($xml['track']['album']['song'])){
		$stream['album']['title'] = $xml['track']['album']['title'];
		$stream['album']['lastfm_url'] = $xml['track']['album']['url'];
	}
	$stream['track']['lastfm_url'] = $xml['track']['url'];
	if(isset($xml['track']['artist']['url'])){
		$stream['artist']['lastfm_url'] = $xml['track']['artist']['url'];
	} else {
		$stream['artist']['lastfm_url'] = 'http://www.google.com/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']);
	}
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
	return $stream;

}
	
//Get extra information of the album
function getAlbumInfo($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=album.getinfo&artist='.urlencode($stream['info']['artist']).'&album='.urlencode($stream['album']['song']).'&api_key='.LAST_FM_API);
	$url = str_replace('%20','+',$url);
	
	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);
	
	//Get the album release date
	if ($xml['album']['releasedate'] && strlen($xml['album']['releasedate']) > 10){
		$stream['album']['releasedate'] = reset(explode(",",$xml['album']['releasedate']));
	}
	
	//Get the album tracklisting
	if(isset($xml['album']['tracks']['track'])){
		foreach($xml['album']['tracks']['track'] as $track){
			$stream['album']['track_list'][] = array('title' => $track['name'],'url' => $track['url']);
		}
	}
	
	//Get the informatin of the current album
	if(isset($xml['album']['wiki']['summary'])){
		$stream['album']['summary'] = $xml['album']['wiki']['summary'];
		$stream['album']['info'] = $xml['album']['wiki']['content'];
	}
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
	return $stream;
}

//Get extra information of the artist		
function getArtistInfo($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist='.urlencode($stream['info']['artist']).'&api_key='.LAST_FM_API.'&autocorrect=1');
	$url = str_replace('%20','+',$url);

	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);		
	
	//Get the top albums of the artist
	//if(isset($xml['topalbums']['album'])){
	//	foreach($xml['topalbums']['album'] as $album){
	//		$stream['artist']['top_albums'][] = array('title'=>$album['name'], 'url'=>$album['url'], 'image'=>$album['image']);
	//	}
	//}
	
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist='.urlencode($stream['info']['artist']).'&api_key='.LAST_FM_API.'&autocorrect=1');
	$url = str_replace('%20','+',$url);

	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);
	
	//Get the cover of the artist
	if(isset($xml['artist']['image'])){
		$stream['artist']['image_s'] = $xml['artist']['image'][0];
		$stream['artist']['image_m'] = $xml['artist']['image'][1];
		$stream['artist']['image_l'] = $xml['artist']['image'][2];
	}	
	
	//Get the bio of the artist
	if(isset($xml['artist']['bio']['summary'])){
		$stream['artist']['summary'] = $xml['artist']['bio']['summary'];
		$stream['artist']['info'] = $xml['artist']['bio']['content'];
	}
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
	return $stream;
}

//get the buylink   
function getTrackBuyLink($stream){
	$url = str_replace('#','','http://ws.audioscrobbler.com/2.0/?method=track.getBuylinks&artist='.urlencode($stream['info']['artist']).'&track='.urlencode($stream['info']['song']).'&api_key='.LAST_FM_API.'&country='.urlencode('united states').'&autocorrect=1');
	$url = str_replace('%20','+',$url);

	$xml = @simplexml_load_file($url,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = obj_to_array($xml);	

        if(isset($xml['affiliations']['physicals']['affiliation'])){
                foreach($xml['affiliations']['physicals']['affiliation'] as $buy){
                        $supplier = str_replace('iTuens', 'iTunes', $buy['supplierName']);
                        if($buy['isSearch'] == 0){
                                $new = array('link' => $buy['buyLink'], 'price'=>$buy['price']['amount'], 'currency'=>$buy['price']['currency'], 'icon'=>$buy['supplierIcon']);
                        }
                        else{
                                $new = array('link' => $buy['buyLink'],'icon'=>$buy['supplierIcon']);
                        }
                        $stream['track']['buylink']['physical'][$supplier] = $new;
                }
        }
        if(isset($xml['affiliations']['downloads']['affiliation'])){
                foreach($xml['affiliations']['downloads']['affiliation'] as $buy){
                        $supplier = str_replace('Amazon MP3', 'Amazon', $buy['supplierName']);
                        if($buy['isSearch'] == 0){
                        
                        		//$new = array('link' => $buy['buyLink'], 'price'=>$buy['price']['amount'], 'currency'=>$buy['price']['currency'], 'icon'=>$buy['supplierIcon']);                       
                                $new = array('link' => $buy['buyLink'],'icon'=>$buy['supplierIcon']);
                                
                        }
                        else{
                                $new = array('link' => $buy['buyLink'],'icon'=>$buy['supplierIcon']);
                        }
                        $stream['track']['buylink']['download'][$supplier] = $new;
                }
        }
	if(isset($xml['error'])){
		$stream['error'] = $xml['error'];
	}
        return $stream;
}


		
//Get lyrics from chartlyrics.com's API
function getLyric($artist, $song){
	$url = str_replace('\'','','http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist='.urlencode($artist).'&song='.urlencode($song));
	$feed = @file_get_contents($url);
	$info = simplexml_load_string($feed);
	$xml = obj_to_array($info);

	if($xml['LyricId'] && ($xml['Lyric'] != array())){
		return $xml['Lyric'];
	}
	else{
		return 'Sorry, there\'s no lyric found for this song';
	}
}

function getInfo($stream){
	if(!$stream['info']['song']){
		$stream['info']['song'] == 'Not found';
		return $stream;
	}
	if(GET_TRACK_INFO == TRUE){
		$stream = getTrackInfo($stream);
	}
	if(GET_ALBUM_INFO && isset($stream['album']['song'])){
		$stream = getAlbumInfo($stream);
	}
	if(GET_ARTIST_INFO == TRUE){
		$stream = getArtistInfo($stream);
	}
	if(GET_TRACK_BUY_LINK == TRUE){
		$stream = getTrackBuyLink($stream);
	}
	if(GET_LYRICS == TRUE){
		$stream['track']['lyric'] = getLyric($stream['info']['artist'], $stream['info']['song']);
	}
	$stream['fetch_time'] = time();
	return $stream;
}

function array_encode($array){
	foreach($array as $key=>$value){
		if(is_array($value)){
			$array[$key] = array_encode($value);
		}
		else{
			$array[$key] = base64_encode($value);
		}
	}
	return $array;
}

function array_decode($array){
	foreach($array as $key=>$value){
		if(is_array($value)){
			$array[$key] = array_decode($value);
		}
		else{
			$array[$key] = base64_decode($value);
		}
	}
	return $array;
}

function cacheVar($stream){
	$stream = array_encode($stream);
	file_put_contents('var/info.json', json_encode($stream));
}

function init($stream){
	$stream['album']['image_s'] = $stream['album']['image_m'] = $stream['album']['image_l'] = $stream['album']['image_xl'] = DEFAULT_ALBUM_ART;
	$stream['track']['summary']  = $stream['track']['info'] = "No information found for this track, try searching for <a target='_blank' href='http://www.google.com/search?q=".urlencode($stream['info']['artist']." - ".$stream['info']['song'])."'>".$stream['info']['artist']." - ".$stream['info']['song']."</a> on Google";
	$stream['album']['title'] = 'Not found';
	$stream['album']['lastfm_url'] = 'http://www.google.com/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']);
	$stream['track']['download_cn'] = 'http://www.google.cn/music/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']);
	$stream['album']['summary'] = $stream['album']['info'] = 'No information found for this album, try searching for <a target="_blank" href="http://www.google.com/search?q='.urlencode($stream['info']['artist']." - ".$stream['info']['song']).'">'.$stream['info']['artist']." - ".$stream['info']['song'].'</a> on Google';
	$stream['album']['releasedate'] = 'Unknown';
	$stream['artist']['summary'] = $stream['artist']['info'] = 'No information found for this artist, try searching for <a target="_blank" href="http://www.google.com/search?q='.urlencode($stream['info']['artist']).'">'.$stream['info']['artist'].'</a> on Google';
	return $stream;
}

?>

<?php echo str_replace("Array", "cache/default00.jpg" ,"<img src='{$stream['album']['image_l']}' title='{$stream['album']['title']}' height='250px' width='250px' ></img>"); ?>
<div class="tout">
<h2><i>
	<!-- Name of the Track / Show -->
	<?php echo "{$stream['info']['song']}"; ?>
</i></h2>

<h3>
	<!-- Name of the Artist / Dj -->
	<?php 
	$arr = array("Unknown" => "Live Radio Show");
	echo "<a href='{$stream['artist']['lastfm_url']}' target='_blank'>";
	echo strtr("{$stream['info']['artist']}",$arr);
	echo "</a>";
	?>
</h3>


</div>
 
XNTPbIY сказал(а):
Вот код каторый я пытался адаптировать под свои нужды.

Еще config_now.php  там прописан ключ к lastfm и вкл и отключения сервисов покупки.

По Ласт.фм ничем не могу помочь, я с ним не дружу. ))
 
Назад
Верх