1
我正在嘗試使用last.fm api從last.fm中提取前6名藝術家。我能夠拉入JSON數據並輸出它就好了。但是,當涉及到實際使用特定的數據時,我感到茫然。我只想使用藝術家的名字。這是我迄今爲止的代碼。使用last.fm api返回的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"}]}}}
任何幫助將不勝感激!
我做了此更改,現在收到此錯誤:警告:無效參數爲foreach()提供,位於第47行的/home/xptdbiyf/public_html/instagramTest.php。我只是不確定如何訪問特定的數據段。 –
'$ content'將會是整個數組,所以你試圖訪問一個不存在的變量。藝術家的集合將被'$ content-> artists-> artist'而不是'$ content-> artist'訪問。 – qooplmao
謝謝!你是我的英雄!!!!!!! –