← Other topics

YouTube API & PHP - Get all videos from a channel (google-api-php-client)

Video Notes

Guides in this series:

Intro

In Part 1 of this series we got set up with the Google Cloud console and the package google-api-php-client to query the YouTube data API.

In Part 2, we looked at a an example of getting the details for a single video and we explored the API docs.

Now, in Part 3, we’re going to learn how to get all the public videos from a specific channel, and how to page through the results.

Starting code

# This code assumes you have Composer set up and have required the package google-api-php-client

# You can omit requiring Composer’s autoload file if you’re working in a framework (e.g. Laravel) that sets up autoloading for you
require_once 'vendor/autoload.php';

# Pull in the classes we’ll use from the google-api-php-client package
use Google\Client;
use Google\Service\YouTube;

# Define config
$apiKey = 'YOUR_API_KEY';

# Initialize YouTube API client
$client = new Client();
$client->setDeveloperKey($apiKey);
$service = new YouTube($client);

PlayListItems List

To get all the public videos from a specific channel we’ll use YouTube’s PlayListItems List method.

To begin, we first have to understand that all the public videos uploaded to a channel belong to a special “Upload” playlist. To get the ID of this playlist, you take the channel id and prepend it with U.

For example, my channel id is UCLyz8iEvzxyhKEBzOTs6bJQ so the playlist id for my public videos is UUCLyz8iEvzxyhKEBzOTs6bJQ.

To find out your channel id, visit YouTube and click your account icon on the top right then click View my channel. The URL it takes you to will have your channel id (e.g. https://www.youtube.com/channel/UCLyz8iEvzxyhKEBzOTs6bJQ).

How to find your channel ID in YouTube

Query for upload playlist

Once you’ve identified the upload’s playlist id, you can query for the videos using the PlayListItems List method like so:

$response = $service->playlistItems->listPlaylistItems(
    'snippet',
    ['playlistId' => 'UULyz8iEvzxyhKEBzOTs6bJQ']
);

Paging through results

By default, the above code returns a max of 5 videos at a time. We can increase this to up to 50 videos by adding the maxResults parameter:

$response = $service->playlistItems->listPlaylistItems(
    'snippet',
    ['playlistId' => 'UULyz8iEvzxyhKEBzOTs6bJQ', 'maxResults' => 50]
);

If we’re working with a channel that has more than 50 videos, though, this still leaves us with ”unfetched” videos. In this case, we need to run multiple queries to get all the results.

To do this, first observe three key bits of data that come back as part of the response:

  • nextPageToken
  • prevPageToken
  • pageInfototalResults
nextPageToken and prevPageToken in YouTube API response

The first two bits of data relate to a page token which is used to “page through” results. In the above example, there’s a value for nextPageToken. If we take this value and pass it as a pageToken parameter to our query, we can get the next page of results:

$response = $service->playlistItems->listPlaylistItems(
    'snippet',
    [
        'playlistId' => 'UULyz8iEvzxyhKEBzOTs6bJQ',
        'pageToken' => 'EAAaI1BUOkNESWlFREUzUVRSQ09EQkdSVUV6UWprM09EVW9BVkFC',
        'maxResults' => 50
    ]
);

dump($response);

Output from the above query:

Paginating through YouTube Data API response

Note how this query is at the end of our results, so nextPageToken is now null. However, because we’re on the second “page” of results, we now have a prevPageToken value we could use to query for the previous page.

Next / Previous

Pulling the above info together, we can build a simple paging system using a query string:

<?php

# You can omit requiring Composer’s autoload file if you’re working in a framework (e.g. Laravel) that sets up autoloading for you
require_once 'vendor/autoload.php';

use Google\Client;
use Google\Service\YouTube;
use Google\Service\Exception;

# Configs
$apiKey = 'YOUR_API_KEY';

# Initialize YouTube API client
$client = new Client();
$client->setDeveloperKey($apiKey);
$service = new YouTube($client);

# https://developers.google.com/youtube/v3/docs/playlistItems/list
$response = $service->playlistItems->listPlaylistItems(
    'snippet',
    [
        'playlistId' => 'UULyz8iEvzxyhKEBzOTs6bJQ',
        'pageToken' => $_GET['pageToken'] ?? null,
        'maxResults' => 10,
    ]
);

#dump($response);

# Extract data we need from the response
$prevPageToken = $response->prevPageToken ?? null;
$nextPageToken = $response->nextPageToken ?? null;
$totalResults = $response->pageInfo->totalResults;
$videos = $response->items;
?>

<?php if($prevPageToken): ?>
    <a href='/?pageToken=<?php echo $prevPageToken?>'>Previous page</a>
<?php endif ?>

<?php if($nextPageToken): ?>
    <a href='/?pageToken=<?php echo $nextPageToken?>'>Next page</a>
<?php endif ?>

<?foreach ($videos as $video): ?>
    <div style='margin:10px 0'>
        <img 
        style='width:150px'
        src='<?php echo $video->snippet->thumbnails->high->url ?>' 
        alt='Thumbnail for the video <?php echo $video->snippet->title ?>'><br>

        <strong>Title:</strong> 
        <?php echo $video->snippet->title ?>
        <br>
        <strong>Video ID:</strong> 
        <?php echo $video->snippet->resourceId->videoId ?>
    </div>
<?php endforeach; ?>

Results:

Get all the videos in a single page request

If you don‘t want to page through results, you can set up a loop to query the API multiple times and get all your videos in a single page request. Example:

<?php

require_once 'vendor/autoload.php';

use Google\Client;
use Google\Service\YouTube;
use Google\Service\Exception;

# Configs
$apiKey = 'YOUR_API_KEY';

# Initialize YouTube API client
$client = new Client();
$client->setDeveloperKey($apiKey);
$service = new YouTube($client);

$nextPageToken = null;
$videos = [];

while(!isset($response) || $nextPageToken != null) {

    $response = $service->playlistItems->listPlaylistItems(
        'snippet',
        [
            'playlistId' => 'UULyz8iEvzxyhKEBzOTs6bJQ',
            'pageToken' => $nextPageToken,
            'maxResults' => 50,
        ]
    );

    $nextPageToken = $response->nextPageToken ?? null;

    $videos = array_merge($videos, $response->items);
}

dump($videos);

The result of the above is the $videos variable is an array of all 93 videos on my channel (at the time of this writing):

Use the YouTube API and PHP to get all the videos from a public channel in a single page request

What’s Next?

So far in this series we’ve focussed on retrieving data from the YouTube data API. In the next guide, we’ll set up an OAuth connection so we can start to alter data via the API: YouTube API & PHP - OAuth Connection.

If this info helped you out, toss a coin in the tip jar?
← Other topics