Get all videos from channel with YouTube API

Getting all the videos (data) from a YouTube channel with the API seems a fairly common need right? Fair play to YouTube and Google as they’re going to make you put some thought into getting that result.

There is actually no straight up endpoint to achieve this, however you can retrieve (max 50) the latest videos from a channel and it comes with pagination through the parameter ?pageToken= with the token being found at nextPageToken.

The best part is if there is no next page of results there is no nextPageToken. Thus making the looping of results stop.

Getting all videos from a channel

Here is the code, make sure you put in the channel id and your YouTube API key

$yt_channel_id = '';//YouTube Channel id
$yt_api_key = '';//YouTube API key
function list_videos_w_page($chid, $api_key, $page_token = '')
global $yt_channel_id;
global $yt_api_key;
if ($page_token == '') {
$data = json_decode(file_get_contents("" . $chid . "&maxResults=50&order=date&type=video&key=$yt_api_key"), true);
} else {
$data = json_decode(file_get_contents("" . $chid . "&maxResults=50&order=date&type=video&key=$yt_api_key&pageToken=$page_token"), true);
foreach ($data['items'] as $val) {
$vid = $val['id']['videoId'];//returns video id
$title = str_replace("'", "", $val['snippet']['title']);//returns video title
$desc = str_replace("'", "", $val['snippet']['description']);//returns video description
$uploaded = date('Y-m-d H:i:s', strtotime($val['snippet']['publishedAt']));//returns video description
echo "[$vid]($uploaded) $title<br>";
if (isset($data['nextPageToken'])) {//if exists means there is another page so do:
echo list_videos_w_page($yt_channel_id, $yt_api_key, $data['nextPageToken']);
echo list_videos_w_page($yt_channel_id, $yt_api_key);

view raw


hosted with ❤ by GitHub

Essentially just a looping function, that if there is a nextPageToken the function will self call itself. It will only stop when nextPageToken is not found in the returned results.

Make sure to set it up with a database insert as repeating this code could bring your API limits to exhaustion.