【发布时间】:2016-04-07 13:27:27
【问题描述】:
我有这个非常长的 JSON 字符串:http://pastebin.com/2jJKSGHs,它是从音乐 API 中提取的。
我设置了这段代码来解析它(http://pastebin.com/EuJtuhHg):
$url = "https://api.discogs.com/database/search?type=artist&q=pink[keyandsecretredacted]";
//initialize the session
$ch = curl_init();
//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.com');
//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);
//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the curl session
$output = curl_exec($ch);
//close the session
curl_close ($ch);
//decode and print output
$output = json_decode($output2, true);
echo($output['results'][0]['title']);
当我将 JSON 字符串的内容直接插入到我的代码中时,json_decode 可以完美地处理它。但是当我尝试使用上面的方法从 API 中获取它时,我的页面上什么也没有打印——它只是空的。打印出 json_last_error 返回“0”,所以它没有检测到任何错误。
任何想法为什么会发生这种情况?
【问题讨论】:
-
我将原始 pastebin 的内容复制到
json文件中,将其导入到变量中,使用json_decode,它运行良好。如果json_decode对您不起作用,您的代码中还有其他原因会导致错误。 -
你是对的。我应该在发布之前测试一下。当我将文本直接插入代码时效果很好。由于此文本来自 API,因此我使用 curl 来获取它(pastebin.com/EuJtuhHg)。 /然后/它不起作用。它实际上没有在页面上打印任何内容,当我运行 json_last_error() 它说没有错误。我认为撇号是由于不同的原因造成的,但现在我想知道它是否还有其他原因。
-
啊,我很高兴我回来看看你改变了你展示的东西。您的代码中没有真正的“错误”。你在
$output2上调用json_decode,它什么都不包含,你想在$output上调用它,它完美地工作^^ -
你可以var_export $output的$output = curl_exec($ch);
-
另外,要么删除这个问题,要么标记它,以便模组可以从帖子历史记录中删除你的 api 密钥和秘密。
标签: php json parsing quote apostrophe