YouTube Video Information Using YouTube API


If you want to embed YouTube videos or want to add your video gallery then you can use YouTube API v2 to get all necessary information about the video like video title, description, category, thumbnail and others. In this post I am going to show you how to get YouTube video information using YouTube api.

To get the YouTube video information in JSON format we will use CURL and pass the parameter value “jsonc” in API url. So our function getYoutubeVideoData is as below:

function getYoutubeVideoData($videoUrl){
	$queryString = parse_url( $videoUrl, PHP_URL_QUERY );
	parse_str( $queryString, $query );

	$apiURL = 'http://gdata.youtube.com/feeds/api/videos/'. $query['v'] .'?v=2&alt=jsonc';

	$ci = curl_init();

	/* Curl settings */
	curl_setopt($ci, CURLOPT_URL, $apiURL);
	curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ci, CURLOPT_BINARYTRANSFER, true);
	curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 10 );

	$json_response = curl_exec($ci);
	curl_close ($ci);

	if($data = json_decode($json_response))
		return $data->data;
}

You need to pass the YouTube video URL and it will get the id of video and call the API using CURL.

$youtubeUrl = "https://www.youtube.com/watch?v=xxxxxxxxxx";
$data = getYoutubeVideoData($youtubeUrl);

This way you can get the Video Information Using YouTube API like below:

$data->title;
$data->duration;
$data->description;
$data->thumbnail->sqDefault;
$data->rating;
$data->likeCount;
$data->category;
$data->viewCount;
$data->uploaded;

You can get video information with YouTube API using JavaScript as below:

var video_id='xxxxxxxx';

$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){
alert(data.data.title);
});