0

我正在我的频道上显示最新上传的 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 "";
}

所以我的问题是,如果 resonse 是 403,如何处理(检测)?这样我就可以做其他事情了!

4

2 回答 2

1

您无法使用file_get_contents. 我会使用类似 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;
}
于 2013-01-25T17:13:41.850 回答
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
}
?>
于 2013-01-25T17:14:45.187 回答