我正在使用Youtube数据api v3使用以下网址检索搜索查询的数据 https://www.googleapis.com/youtube/v3/search?part=snippet&q=text&key=apikey&maxResults=25
我正在获取json响应,而我使用json解码来解析json数据,我得到空结果,任何人都可以告诉我如何检索数据
我使用下面的PHP代码来解析
$videourl="https://www.googleapis.com/youtube/v3/search?part=snippet&q=hello&key=apikey&maxResults=25";
$json = file_get_contents($videourl);
$data = json_decode($json,true);
print_r($data);
从以下网址获取json响应: https://www.googleapis.com/youtube/v3/search?part=snippet&q=hello&key=apikey&maxResults=25
答案 0 :(得分:0)
if (extension_loaded('curl')) {
# create a new cURL resource
$ch = curl_init();
# set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://googleapis.com/.....");
curl_setopt($ch, CURLOPT_HEADER, 0);
# Setting cURL's option to return the webpage data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
# grab URL and pass it to the browser
if($json = curl_exec($ch)) {
if(!($data = @json_decode($json)) instanceof stdClass) {
trigger_error('Unable to decode json. '. print_r(error_get_last(), true));
}
}
else trigger_error('CUrl Error:'.curl_error($ch));
# close cURL resource, and free up system resources
curl_close($ch);
}
else trigger_error('CUrl unsupported', E_USER_WARNING);
答案 1 :(得分:-1)
您应该测试file_get_contents的返回值。请注意,如果出现错误(而不是NULL),此函数将返回FALSE。因此,您应该使用=== FALSE
测试返回值,以免被空值混淆。
在您的情况下,如果您尝试访问在问题中发布的确切网址,则Google会返回代码400(错误请求),这就是您返回FALSE的原因。