Get Your API Key
Time needed: 15 minutes
- Go to Google Developers Console & Create a New Project
Visit https://console.cloud.google.com/ & Create a New Project or Select an existing project.
- Enable Youtube data API for this Project
After the project is created, select it and search for Youtube data API in search box.
Now Enable the Youtube data API as shown below –
- Create API key by clicking Create Credentials link
Copy the API Generated in this Step - Get the Youtube Channel Id
Go to your Youtube channel & copy the channel id from URL as shown below –
- Assemble the data into PHP code
Now create your PHP file where you want to fetch the youtube videos via API & put the following code –
PHP Code to fetch data from Youtube API –
<?php
/* Fetch Data from Youtube API */
$channelDATA = file_get_contents('https://www.googleapis.com/youtube/v3/search?channelId=<CHANNEL_ID>&key=<API_KEY>&part=snippet&maxResults=10');
/*Convert the Data into PHP Array */
$YtVideosArr = json_decode($channelDATA)->items;
/*Loop through the items in array */
$video_index = 1;
foreach($YtVideosArr as $singleVideo){
$videoId = $singleVideo->id->videoId;
$thumbnail_url = $singleVideo->snippet->thumbnails->high->url;
$video_title = $singleVideo->snippet->title;
$video_description = $singleVideo->snippet->description;
$published_time = $singleVideo->snippet->publishTime;
echo '<iframe width="280" height="150" src="https://www.youtube.com/embed/'.$videoId.'" frameborder="0" allowfullscreen></iframe>';
echo $video_title;
echo $video_description;
echo $published_time;
}
?>