Get all videos from a playlist (Youtube API v3)

4.8k views Asked by At

I'd like to use the new youtube API to retrieve a list of all the videos (their ID's and titles) from a specific playlist.

I need the id's separated so that I can make a "video gallery" using php on my website, instead of only one video with the playlist sidebar.

This was already working in my website, but since the new API has been implement on June 4th, it's not working anymore.

Any solutions? Thank you.

1

There are 1 answers

2
theduck On BEST ANSWER

There is a PHP sample on the YouTube API site which uses the playlistItems.list call to get a list of videos which you can use to get the information you require.

http://developers.google.com/youtube/v3/docs/playlistItems/list

If you use the YouTube PHP client library then something along these lines will get all video IDs and titles for a specified playlist:

<?php

require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

$client = new Google_Client();
$client->setDeveloperKey('{YOUR-API-KEY}');
$youtube = new Google_Service_YouTube($client);

$nextPageToken = '';
$htmlBody = '<ul>';

do {
    $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
    'playlistId' => '{PLAYLIST-ID-HERE}',
    'maxResults' => 50,
    'pageToken' => $nextPageToken));

    foreach ($playlistItemsResponse['items'] as $playlistItem) {
        $htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'], $playlistItem['snippet']['resourceId']['videoId']);
    }

    $nextPageToken = $playlistItemsResponse['nextPageToken'];
} while ($nextPageToken <> '');

$htmlBody .= '</ul>';
?>

<!doctype html>
<html>
  <head>
    <title>Video list</title>
  </head>
  <body>
    <?= $htmlBody ?>
  </body>
</html>

If you have any problems implementing then please post your code as a new question and someone will be able to assist.