Skip to content
Advertisement

Get YouTube video title in PHP

In one of my applications I am saving a YouTube video’s id… Like “A4fR3sDprOE”. I have to display its title in the application. I got the following code for getting its title and also it’s working fine.

Now the problem is if any error occurred (in case of a delete of the video) PHP is showing an error. I hust added a condition. But still it’s showing the error.

foreach($videos as $video) {

    $video_id = $video->videos;
    if($content=file_get_contents("http://youtube.com/get_video_info?video_id=".$video_id)) {
        parse_str($content, $ytarr);

        $myvideos[$i]['video_title']=$ytarr['title'];

    }
    else
        $myvideos[$i]['video_title']="No title";

    $i++;
}

return $myvideos;

In case of an error it’s dying with the following:

Severity: Warning

Message: file_get_contents(http://youtube.com/get_video_info?video_id=A4fR3sDprOE) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 402 Payment Required

Filename: models/webs.php

Line Number: 128

Advertisement

Answer

It may work to use the error control operators before file_get_contents.

Something like:

if($content = @file_get_contents("http://youtube.com/get_video_info?video_id=" . $video_id))

It should remove the error and use it to return false in your if statement.

Else you can just use try/catch statement (see Exceptions):

try{
    // Code
}
catch (Exception $e){
    // Else code
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement