List YouTube channel videos using YouTube Data API in PHP
Google provides YouTube data API. You can do lots of nice things using it. In this post, I am going to show you how you can retrieve and list YouTube channel videos using YouTube data API in PHP.
Before you do this, you have to get the API from the Google API Console. After you get the API, follow what I am going to do.
The URL that returns the JSON data for a particular YouTube channel is given below:
https://www.googleapis.com/youtube/v3/search?key=".$yt_api."&channelId=".$channelId."&part=snippet,id&order=date&maxResults=20
You can notice that you just have to pass the YouTube Data API and channel ID to get the list.
Now let’s see our coding in PHP to retrieve videos from a particular YouTube channel using YouTube data API.
At first, take the API and channel ID in PHP variables and then request to the API URL just like below:
<?php $yt_api = "YOUTUBE_DATA_API_KEY"; $channelId = "YOUTUBE_CHANNEL_ID"; $yt_api_url = "https://www.googleapis.com/youtube/v3/search?key=".$yt_api."&channelId=".$channelId."&part=snippet,id&order=date&maxResults=20"; $yt_json = file_get_contents($yt_api_url); ?>
The URL will return JSON data which we have to decode using PHP json_decode() function that you can see below:
$yt_arr = json_decode($yt_json);
After we decode the JSON data we will get videos from the channel in an array. The array contains 20 videos of the channel as we set the maxResults URL parameter to 20 in the URL. If you want a different number of videos on a page, then you can change it.
From the array, we can list each videos using PHP foreach loop.
List channel videos with PHP foreach loop
Below is the loop that will extract each and every thumbnail URL and display it on the web page with HTML img tag:
<?php foreach ($yt_arr->items as $item) { // echo "<pre>"; print_r($item->id->videoId); echo "</pre>"; $videoId = $item->id->videoId; $thumb_url = $item->snippet->thumbnails->medium->url; ?> <a href="https://www.youtube.com/watch?v=<?php echo $videoId; ?>"> <img style="margin: 1px;border:solid 1px #000" src="<?php echo $thumb_url; ?>"> </a> <?php } ?>
In the above code, we are extracting the medium size thumbnail. Also, all the thumbnails are inside the anchor link. We extract the video ID and pass it to the YouTube video page. In our example, we have only extracted the medium size thumbnail URL and the video ID.
By printing the array on the page, you can get all other items in the array and use any item depending on your needs or requirement.
I dont know where to get $yt_api = “YOUTUBE_DATA_API_KEY”;