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.
Here is the code, make sure you put in the channel id and your YouTube API key
<?php | |
$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("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" . $chid . "&maxResults=50&order=date&type=video&key=$yt_api_key"), true); | |
} else { | |
$data = json_decode(file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" . $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); |
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.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…