使用 PHP 解析 Last.FM API
我对此很陌生,所以请忍受我的新手问题。
基本上,我希望用户在网络表单中输入搜索短语,并将查询传递到lastFM API,并根据他们的“gettopartists”API 节点使用该短语返回顶级艺术家。这是我的代码...
function last($q) {
$target_url='http://ws.audioscrobbler.com/2.0/format=json&method=tag.gettopartists&api_key=....&tag=' . $q . '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$return = curl_exec($ch);
}
显然,在其中我通过打印“echo $return;”获得了有效的返回值但我不知道如何正确解析它。无论我输入多少个 foreach 参数,我都无法避免错误或根本没有输出......
谢谢大家......
I'm new to this so bear with my noobish question.
Basically I want a user to enter a search phrase into a web-form and for the query to be passed to the lastFM API and return top artists using that phrase based on their "gettopartists" API node. Here's the code I have...
function last($q) {
$target_url='http://ws.audioscrobbler.com/2.0/format=json&method=tag.gettopartists&api_key=....&tag=' . $q . '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$return = curl_exec($ch);
}
Obviously within that I get a valid return by printing "echo $return;" but I've no idea how to parse it correctly. No matter how many foreach arguments I put in I cannot avoid an error or no output at all...
Thanks folks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设您正在谈论此功能: http://www.last.fm/api /show?service=300
如果省略 format=json 部分,它将以 xml 形式返回
示例响应看起来像是 XML 格式,在这种情况下,您可以使用 PHP 的 SimpleXML 解析它 http://php.net/manual/en/ref.simplexml.php
http://www.ibm.com/developerworks/library/x-simplexml.html
你还有format=json,这让我相信它可能会以JSON格式返回,在这种情况下你会使用json_decode。
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
echo $obj->{'foo-bar'}; // 12345
I assume you are talking about this function: http://www.last.fm/api/show?service=300
If you leave out the format=json part, it will get returned as xml
The sample response looks like it's in XML format, in that case you can parse it with PHP's SimpleXML http://php.net/manual/en/ref.simplexml.php
http://www.ibm.com/developerworks/library/x-simplexml.html
You also have format=json, which leads me to believe that it might be returned in JSON format, in which case you would use json_decode.
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
echo $obj->{'foo-bar'}; // 12345
您应该查看 json_decode 的 PHP 文档。它从 JSON 构建一个 stdClass 对象(或关联数组),您可以将它们循环到您心中的内容。
You should take a look at the PHP documentation for json_decode. It builds a stdClass object (or associative arrays) from JSON which you can them loop over to your hearts content.