我试图理解递归:)好吧,特别是使用Google的PHP客户端库获取完整的YouTube播放列表。

这是我的类YTFunctions中的函数。首先使用有效的,经过身份验证的YouTube_Service对象和playlistId进行调用。然后,理论上,只要PlaylistItems响应具有nextPageToken,它就应该一次又一次地调用自身,然后将其附加到其输出中,该输出应包含播放列表中包含的所有对象(视频)。由于某种原因,它只是返回一个空数组。

public static function getFullPlaylistByID($youtube, $playlistId, $pageToken) {
    $params = array(
        'maxResults' => 50,
        'playlistId' => $playlistId,
    );
    if ($pageToken !== false) {
        $params['pageToken'] = $pageToken;
    }
    $playlistResponse = $youtube->playlistItems->listPlaylistItems('snippet,contentDetails', $params);
    error_log(count($playlistResponse['items']));
    $playlistItems = $playlistResponse['items'];
    if (isset($playlistResponse['nextPageToken'])) {
        $playlistItems = array_merge($playlistItems, YTFunctions::getFullPlaylistByID($youtube,$playlistId, $playlistResponse['nextPageToken']));
    } else {
    }
    return $playlistItems;
}

我显然在这里缺少任何东西,任何帮助将不胜感激。

托比亚斯·蒂姆佩

最佳答案

这是我的类(class),将获得所有播放列表项

<?php
class yt{
    public $DEVELOPER_KEY = '{DEVELOPER_KEY}';
    public $client;
    public $youtube;

    public function __construct(){
        $this->client = new Google_Client();
        $this->client->setDeveloperKey($this->DEVELOPER_KEY);
        $this->youtube = new Google_YoutubeService($this->client);
    }

    public function getPlaylistItems($playlist, $maxResults, $nextPageToken = ''){
        $params = array(
            'playlistId' => $playlist,
            'maxResults' => $maxResults,
        );

        // if $nextPageToken exist
        if(!empty($nextPageToken)){
            //insert $nextPageToken value into $params['pageToken']
            $params['pageToken'] = $nextPageToken;
        }

        $youtubeFeed = $this->youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', $params);
        // function for looping our feed and entry
        $this->setFeed($youtubeFeed);

        //check if nextPageToken are exist
        if(!empty($youtubeFeed['nextPageToken'])){
            $insert = $this->getPlaylistItems($playlist, $maxResults, $youtubeFeed['nextPageToken']);
            // return to function if nextPageToken are exist
            return $insert;
        }

    }
}

$yt = new yt();

?>

而不是使用我们的类(class)
$yt->getPlaylistItems('PL0823049820348','25');

关于php - YouTube API:获取完整的播放列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20598758/

10-13 03:35