我正在频道上展示最新上传的YouTube视频。它工作正常,但不时会出现此错误,并导致我的整个网站出错!
[phpBB Debug] PHP Warning: in file /my_youtube/functions.php on line 5:
file_get_contents(http://gdata.youtube.com/feeds/api/users/ElectronicsPubVideos/uploads?v=2&alt=json&max-results=5&orderby=published):
failed to open stream:
HTTP request failed! HTTP/1.0 403 Forbidden
我不知道什么是探测器,可能是youtube方面的时间错误?无论如何这是我解析JSON文件的函数(如果实际上是从youtube返回的话):
function GetLatestVideos()
{
$url = file_get_contents('http://gdata.youtube.com/feeds/api/users/ElectronicsPubVideos/uploads?v=2&alt=json&max-results=5&orderby=published');
$i = 0;
if($result = json_decode($url, true))
{
foreach($result['feed']['entry'] as $entry)
{
$vids[$i]["title"] = $entry['title']['$t'];
$vids[$i]["desc"] = $entry['media$group']['media$description']['$t'];
$vids[$i]["thumb"] = $entry['media$group']['media$thumbnail'][2]['url'];
$vids[$i]["url"] = $entry['link'][0]["href"];
$vids[$i]["id"] = $entry['media$group']['yt$videoid']['$t'];
$i++;
}
return $vids;
}
else return "";
}
所以我的问题是,如果共振是403,如何处理(检测)?所以我可以做别的事情!
答案 0 :(得分:0)
您无法使用file_get_contents
读取HTTP标头。我会使用像cURL这样的东西:
function get_youtube_content($url)
{
if(!function_exists('curl_init'))
{
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($http_status == '403') ? false : $output;
}
答案 1 :(得分:0)
您可以在函数前添加“@”以防止PHP错误消息:
@file_get_contents
在if条件下使用它:
<?php
if($url = @file_get_contents("http://something/")) {
// success code and json_decode, etc. here
} else {
// error message here
}
?>