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
It's not safe to use file_get_contents() with remote URLs. Use cURL instead with YouTube API 2.0:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds/api/videos/' . $video_id);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
$xml = new SimpleXMLElement($response);
$title = (string) $xml->title;
} else {
// Error handling.
}
This is my solution. It´s very short.
$id = "VIDEO ID";
$videoTitle = file_get_contents("http://gdata.youtube.com/feeds/api/videos/${id}?v=2&fields=title");
preg_match("/<title>(.+?)<\/title>/is", $videoTitle, $titleOfVideo);
$videoTitle = $titleOfVideo[1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With