当我尝试遍历简单 XML 对象时循环不起作用
我试图循环访问 Last.fm API 的结果,但它不起作用。
function get_url($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$xml = get_url('http://ws.audioscrobbler.com/2.0/?method=album.search&album=kid%20a&api_key=b25b959554ed76058ac220b7b2e0a026');
$doc = new SimpleXMLElement($xml);
$albums = $doc->results->albummatches;
foreach($albums as $album){
echo $album->album->name;
}
这只是显示第一张专辑。如果我将 foreach 循环中的代码更改为 echo $album->name;
它什么也不显示。
我做错了什么?
I'm trying to loop through the results from the Last.fm API but it's not working.
function get_url($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$xml = get_url('http://ws.audioscrobbler.com/2.0/?method=album.search&album=kid%20a&api_key=b25b959554ed76058ac220b7b2e0a026');
$doc = new SimpleXMLElement($xml);
$albums = $doc->results->albummatches;
foreach($albums as $album){
echo $album->album->name;
}
This just shows the first album. If I change the code within the foreach loop to echo $album->name;
it shows nothing at all.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用这个怎么样:
这似乎可以获取专辑名称列表。
简而言之,您必须循环
$doc->results->albummatches->album<,而不是循环
$doc->results->albummatches
/代码>。然后,在循环内,
$album
对应于当前专辑;因此,您可以使用$album->name
What about using this :
This seems to get the list of albums names.
To make things short, instead of looping over
$doc->results->albummatches
, you have to loop over$doc->results->albummatches->album
.And, then, inside the loop,
$album
corresponds to the current album ; so, you can use$album->name