How to get a list of videos in YouTube channel using PHP & YouTube API

YouTube offers various powerful ways to play around with videos. You can create awesome applications using the YouTube API and also can embed videos from your YouTube channel.

This tutorial demonstrates how to use YouTube Data API v3 to Integrate YouTube videos and functionality into your website.

Getting started by obtaining  a YouTube API Key & YouTube Channel ID

Generate an API key:

  1. Go to Google Developers Console and log in with your Google/YouTube ID.
  2. Create a new project.
  3. Go to your project and select ‘APIs’ from the sidebar
  4. In the list of APIs select ‘YouTube Data API v3’ and make sure that it’s enabled.
  5. From sidebar, select ‘Credentials’ and click ‘Create New Key’ to generate an API key for your development.

Find your YouTube channel ID

  1. Sign in to your YouTube account.
  2. Goto ‘Settings’.
  3. Next to your profile photo, click ‘Advanced’.
  4. You can find your channel ID under ‘Account information.’

Once you have the API Key & Channel ID, you can retrieve video list from YouTube using the following PHP code:


$myApiKey="#########"; // Provide your API Key
$myChannelID="##########"; // Provide your Channel ID
$maxResults="10"; // Number of results to display

// Make an API call to store list of videos to JSON variable
$myQuery = "https://www.googleapis.com/youtube/v3/search?key=$myApiKey&channelId=$myChannelID&part=snippet,id&order=date&maxResults=20";
$videoList = file_get_contents($myQuery);

// Convert JSON to PHP Array
$decoded = json_decode($videoList, true);

// Run a loop to display list of videos
foreach ($decoded['items'] as $items)
{
$id = $items['id']['videoId'];
$title= $items['snippet']['title'];
$description = $items['snippet']['description'];
$thumbnail = $items['snippet']['thumbnails']['default']['url'];

// Display list with some basic CSS formatting
echo "
<p style='display:inline-block;width:200px;margin:10px;text-align:center;vertical-align:top'>";
echo "<img src='$thumbnail'>
";
echo "<strong>$title</strong>
";
echo "<small>$description</small>";
echo "

";
}

That was a simple example on how to retrieve and display video title, description and some other associated data from your YouTube channel.

Of course, you can do lot more with this API. Refer the Google API documentation.

Advertisements