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
My solution is:
$xmlInfoVideo = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos/" . $videoId . "?v=2&fields=title");
foreach($xmlInfoVideo->children() as $title) {
$videoTitle = strtoupper((string) $title);
}
This get the title of the video.
Try:
// Use @ to suppress warnings
$content = @file_get_contents("http://youtube.com/get_video_info?video_id=" . $video_id);
if($content===FALSE) {
.. Handle error here
}
else{
..The rest of your code
}
I believe your hosting provider disabled file_get_contents for security purposes. You should use cURL.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://youtube.com/get_video_info?video_id=" . $video_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
/* Parse YouTube's response as you like below */
?>
I would like to add to this that the specific error seen here (HTTP 402 - Payment Required, which is otherwise a HTTP status code that servers generally don't have implemented) is what YouTube returns when it has determined that an "excessive" amount of traffic has been coming from your IP address (or IP address range -- they do rather enjoy blocking OVH's IP address ranges on a frequent basis[1][2]).
Therefore, if you're accessing youtube.com (not the API) programmatically (using PHP or otherwise), you may eventually find yourself hitting this error. YouTube generally starts off by presenting CAPTCHAs to requests from "excessive traffic" IP addresses, but if you aren't completing them (which your PHP script won't be), they will switch to these unhelpful 402 responses with essentially no recourse - YouTube doesn't exactly have a customer support desk to call, and if you can't actually access any of their website because of the IP address blocking, you have even less chance of contacting them.
Other references:
http://productforums.google.com/forum/#!topic/youtube/tR4WkNBPnUo
http://productforums.google.com/forum/?fromgroups=#!topic/youtube/179aboankVg
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];