Get Videos from a YouTube channel using PHP and YouTube API

Recently, I was working with my tech blog’s (Techlomedia) mobile app and I thought to include the video section there. As it requires the use of API, I thought to put the same tutorial on this blog as well.
YouTube API offers various methods and allows you to get the videos, video data, upload, update and delete. In this article, I will show you how to fetch the latest video of a channel using the YouTube API.
Before the coding part, you need to have the API key to access the YouTube data. So, open Google API Console and enable the YouTube API for your developer account. Once you have enabled the API, you can create the API key from the credential section.
If you are still not sure how to get the API key, you can watch the video below.
Once you have the API access, you are ready to start with YouTube API.
Now we can start fetching the videos. Use the eblow code to fetch the videos of your own YouTube channel.
$key=YOUR_API_KEY; $channel=YOUR_CHANNEL_ID; $results=6; $url = "https://www.googleapis.com/youtube/v3/search?key=".$key."&channelId=".$channel."&part=snippet,id&order=date&maxResults=$results"; $content = file_get_contents($url); $data = json_decode($content); foreach($data->items as $video) { echo("<br /> Video Id : ".$video->id->videoId); //Video Id. you can use it to create video URL or embed URL echo("<br /> Video Title : ".$video->snippet->title); //Title of the video echo("<br /> Video Title : ".$video->snippet->thumbnails->medium->url); //Thumbnail. There are different sizes. Use as per your interest. }
The above code will work fine if you know the Channel id. If you want to fetch videos from other channels. You need to first get the channel id from username. Username is publicly available in the URL of a channel. So, I don’t think you will face any problem.
Now use the below function in your code that will return the Channel ID.
function getChannelId($username) { $url = "https://www.googleapis.com/youtube/v3/channels?key=".$key."&forUsername=".$username."&part=id"; $content = file_get_contents($url); $data = json_decode($content); $a = $data->items; $channelid = $a[0]->id; return $channelid; }
There are more API methods you can try to get more data as per your need. You can also use the existing API code with more data filters to get the relevant information from YouTube channels.
Read this official API documentation to know more about YouTube API.
If you want to create a complex application using YouTube API, you can hire me for web application or mobile application. I can help you in this. Use contact page to contact me or comment below.
If you have anything to ask, you can comment below.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.