PHP: YouTube v3 API... Retrieve last 50 videos from Watch Later list and add them to a playlist

510 Views Asked by At
<?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>

How to do it for the Watch Later Playlist? Already have the API key. Then, for any videoId -> insert the video in another playlist...

Can you help me?

1

There are 1 best solutions below

8
On BEST ANSWER

If you call:

GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true&key‌​={YOUR_API_KEY} 

you can get the playlistId of your watch later list (under watchLater). You need to authenticate to get the results. If this is a one off thing then use the API explorer:

https://developers.google.com/youtube/v3/docs/channels/list.

Once you have the playlistId then you can use the code in your question to get the videos (and videoIDs) from the list. You will need to add OAuth authentication code before making the call examples here:

https://developers.google.com/youtube/v3/code_samples/php

To upload a video into a new playlist there is a PHP sample in the API docs here:

https://developers.google.com/youtube/v3/code_samples/php#resumable_uploads