How can I retrieve YouTube video details from video URL using PHP?
Yet another URL API that can be helpful is: https://www.youtube.com/get_video_info?video_id=B4CRkpBGQzU
video_id is "v" argument of youTube. Result is a dictionary in URL-encoded format (key1=value1&key2=value2&...)
This is undocumented API existing for long time, so exploring it is up to developer. I am aware of "status" (ok/fail), "errorcode" (100 and 150 in my practice), "reason" (string description of error). I am getting duration ("length_seconds") this way because oEmbed does not provide this information (strange, but true) and I can hardly motivate every employer to get keys from youTube to use official API
You can get data from youtube oembed interface in two formats: XML and JSON
Interface address: http://www.youtube.com/oembed?url=youtubeurl&format=json
Use this PHP function to get data
function get_youtube($url){
$youtube = "http://www.youtube.com/oembed?url=". $url ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
$url = // youtube video url
// Display Data
print_r(get_youtube($url));
Don't forget to enable extension=php_curl.dll
in your php.ini
This returns metadata about a video:
http://www.youtube.com/oembed?url={videoUrlHere}&format=json
Using your example, a call to:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=B4CRkpBGQzU&format=json
Returns the following, which you can digest and parse with PHP:
{
"provider_url": "http:\/\/www.youtube.com\/",
"thumbnail_url": "http:\/\/i3.ytimg.com\/vi\/B4CRkpBGQzU\/hqdefault.jpg",
"title": "Joan Osborne - One Of Us",
"html": "\u003ciframe width=\"459\" height=\"344\" src=\"http:\/\/www.youtube.com\/embed\/B4CRkpBGQzU?fs=1\u0026feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e",
"author_name": "jzsdhk",
"height": 344,
"thumbnail_width": 480,
"width": 459,
"version": "1.0",
"author_url": "http:\/\/www.youtube.com\/user\/jzsdhk",
"provider_name": "YouTube",
"type": "video",
"thumbnail_height": 360
}
To get youtube video description
, different sized thumbnail
, tags
, etc use updated v3 googleapis
Sample URL: https://www.googleapis.com/youtube/v3/videos?part=snippet&id=7wtfhZwyrcc&key=my_google_api_key
$google_api_key = 'google_api_key';
$video_id = 'youtube_video_id';
$api_url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id='.$video_id.'&key='.$google_api_key;
$json = file_get_contents($api_url);
$obj = json_decode($json);
var_dump($obj);