我试图使用last.fm api从last.fm拉出前6位艺术家。我能够提取JSON数据并输出它就好了。但是,当涉及到实际使用特定数据时,我很茫然。我唯一想要使用的是艺术家的名字。这是我到目前为止的代码。
<?php
$content = get_data('http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=xxxxxxxxxxxxxx&format=json&limit=6');
foreach ($content->artist as $artist) {
echo '<li>';
echo "{$artist->name}\n";
echo '</li>';
}
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
数据如下所示:
{"artists":{"artist":[{"name":"Coldplay","playcount":"757749","listeners":"111884","mbid":"cc197bad-dc9c-440d-a5b5-d52ba2e14234","url":"http:\/\/www.last.fm\/music\/Coldplay","streamable":"1","image":[{"#text":"http:\/\/userserve-ak.last.fm\/serve\/34\/210303.jpg","size":"small"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/64\/210303.jpg","size":"medium"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/126\/210303.jpg","size":"large"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/252\/210303.jpg","size":"extralarge"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/500\/210303\/Coldplay.jpg","size":"mega"}]},{"name":"Rihanna","playcount":"943551","listeners":"102321","mbid":"69989475-2971-49aa-8c53-5d74af88b8be","url":"http:\/\/www.last.fm\/music\/Rihanna","streamable":"1","image":[{"#text":"http:\/\/userserve-ak.last.fm\/serve\/34\/79835799.png","size":"small"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/64\/79835799.png","size":"medium"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/126\/79835799.png","size":"large"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/252\/79835799.png","size":"extralarge"},{"#text":"http:\/\/userserve-ak.last.fm\/serve\/_\/79835799\/Rihanna+PNG.png","size":"mega"}]}}}
非常感谢任何帮助!
答案 0 :(得分:1)
您需要使用json_decode
return json_decode($data);
。这将转换您可以进行的对象中的返回数据。对于关联数组,请使用return json_decode($data, true);
。见http://php.net/manual/en/function.json-decode.php