Get YouTube Video Info using YouTube API via PHP

Are you looking for ways to get YouTube video info via API using PHP?

Then this post is for you. I’ll show how to do that using YouTube API v3. Furthermore, I will provide tips on getting YouTube Video ID from Video URL.

To get started, all you need is to create or obtain API Key, which I have covered in my previous article Retrieve YouTube playlist videos using YouTube API.

Getting YouTube Video Info using YouTube API v3

The request URL for Video API is as follows:

GET https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={VIDEO_ID}&key={YOUR_API_KEY}

All you need to do is call this URL with your Video ID and API Key. Most noteworthy, the part parameter specifies a comma-separated list of one or more video resource properties that the API response will include

When you call the above API, it will respond back with JSON data containing snippet, content details and statics about the Video.

The snippet contains information like Video title, description, channel Id, Published Time, Thumbnail URL and so on.

The contentDetails contains data like duration, dimension and so on.

Finally, statistics contains statistical data like view count, like count, dislike count, favorite count and comment count.

Implementation

So far, we have discussed about YouTube API. Now it’s time for implementation. As an example, I’ll use this cute video: https://www.youtube.com/watch?v=1ejTKov_Sm4

In the above YouTube Video URL, Video ID is “1ejTKov_Sm4”. Alternatively, you can use the following function to get YouTube Video ID.

function getYouTubeVideoID($url) {
    $queryString = parse_url($url, PHP_URL_QUERY);
    parse_str($queryString, $params);
    if (isset($params['v']) && strlen($params['v']) > 0) {
        return $params['v'];
    } else {
        return "";
    }
}


// Getting Video ID
$video_url = 'https://www.youtube.com/watch?v=1ejTKov_Sm4';


echo getYouTubeVideoID($video_url); // Output: 1ejTKov_Sm4

 

The following snippet shows how to get video information using PHP.

<?php


  $api_key = 'YOUR_API_KEY';
  
  $video_url = 'https://www.youtube.com/watch?v=1ejTKov_Sm4';
  
  $api_url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=' . getYouTubeVideoID($video_url) . '&key=' . $api_key;
        
  $data = json_decode(file_get_contents($api_url));
  
  // Accessing Video Info
  echo '<strong>Title: </strong>' . $data->items[0]->snippet->title . '<br>';
  echo '<strong>publishedAt: </strong>' . $data->items[0]->snippet->publishedAt . '<br>';
  echo '<strong>Duration: </strong>' . $data->items[0]->contentDetails->duration . '<br>';
  echo '<strong>Duration: </strong>' . $data->items[0]->statistics->viewCount . '<br>';
  
?>

 

In this way, we can easily fetch YouTube Video Information using YouTube v3 API. In my next article, I will discuss how to search YouTube videos using YouTube API.

 

Leave a Reply