Youtube API (PHP) - how to add (existing) video to

2020-03-26 05:07发布

问题:

I am using Youtube API to upload some video, but I can't figure out how to add uploaded video to specific playlist. I have searched all over Google and I haven't found any help at all.

I have read developers guide and I found this - https://developers.google.com/youtube/2.0/developers_guide_php#Adding_a_Playlist_Video, but I don't know how to define which video to which existing playlist I want the script to add.

This is what I use now to upload video:

require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); 

$developerKey = 'MYDEVKEY';
$applicationId = 'SOMEID';

$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
              $username = 'user',
              $password = 'pass',
              $service = 'youtube',
              $client = null,
              $source = 'something', 
              $loginToken = null,
              $loginCaptcha = null,
              $authenticationURL);  

    $clientId = 'something';

    $yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);

    $videoName = "video/user_12345.mov";

    $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
    $filesource = $yt->newMediaFileSource($videoName);
    $filesource->setContentType('video/quicktime');
    $filesource->setSlug('video/test.mov');
    $myVideoEntry->setMediaSource($filesource);
    $myVideoEntry->setVideoTitle('Video title');
    $myVideoEntry->setVideoDescription('Video description');
    $myVideoEntry->setVideoCategory('Autos');
    $myVideoEntry->SetVideoTags('car');
    $uploadUrl ='https://uploads.gdata.youtube.com/feeds/users/default/uploads';

    $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
    $state = $newEntry->getVideoState();
    $idv = $newEntry->getVideoId();

回答1:

The code in the doc you linked to gives you a starting point:

$postUrl = $playlistToAddTo->getPlaylistVideoFeedUrl();
// video entry to be added
$videoEntryToAdd = $yt->getVideoEntry('4XpnKHJAok8');

// create a new Zend_Gdata_PlaylistListEntry, passing in the underling DOMElement of the VideoEntry
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());

// post
try {
  $yt->insertEntry($newPlaylistListEntry, $postUrl);
} catch (Zend_App_Exception $e) {
  echo $e->getMessage();
}

Instead of 4XpnKHJAok8 in that example, you'd want to pass in the id of the new video, i.e. the $idv value in your script.

That code assumes that you have a $playlistToAddTo object already, but you probably will have a playlist ID instead. You can modify it to read

$postUrl = sprintf('https://gdata.youtube.com/feeds/api/playlists/%s?v=2', $playlistId);

where $playlistId is the ID of the playlist you want to add the video to.