JSON 使用 cURL 抓取时无法解析文本?
JSON text unparseable when using cURL to grab it?
我有这个很长的 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 returns“0”,所以它没有检测到任何错误。
知道为什么会发生这种情况吗?
替换
$output = curl_exec($ch);
和
$output2 = curl_exec($ch);
否则$output2
未定义,json_decode
正在使用未定义的变量:
$output = json_decode($output2, true);
我有这个很长的 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 returns“0”,所以它没有检测到任何错误。
知道为什么会发生这种情况吗?
替换
$output = curl_exec($ch);
和
$output2 = curl_exec($ch);
否则$output2
未定义,json_decode
正在使用未定义的变量:
$output = json_decode($output2, true);