0

I am showing the latest uploaded youtube videos on my channel. It works fine but from time to time it gives this error, and renders my entire site in error!

[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 

I don't know what is the probem, might be a time to time error from youtube side? Anyway this is my function that parses the JSON file (If it actually get returned from 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 "";
}

So my question is, how to handle (detect) if resonse is 403? so that I can do something else!

4

2 に答える 2

1

を使用してHTTPヘッダーを読み取ることはできません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 に答える