1

我正在尝试使用 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"}]}}}

任何帮助将不胜感激!

4

1 回答 1

1

你需要使用json_decodeso return json_decode($data);。这会将返回数据转换为您可以遍历的对象。对于关联数组,请使用return json_decode($data, true);. 见http://php.net/manual/en/function.json-decode.php

于 2012-12-09T04:51:09.913 回答