php - YouTube API v3 : How to get returned 404 (not found) error from PlaylistItems?

标签 php youtube-api

我知道我可以循环播放列表以比较播放列表是否存在于 Youtube 上,但这是进行两次调用(下面的示例),并且由于我已经知道播放列表 ID,所以我应该只能进行一次调用。

两次调用 YouTube 以循环播放列表(这不是我想要的方式):

# Playlist ID from URL
$playlist=$_GET['playlist'];

# Playlists from YoUtube
$playlists=$yt->PlaylistsListFeed();

# Loop through the playlists.
foreach($playlists as $playlist_feed)
{
    if($playlist_feed['id']==$playlist)
    {
        # This is a playlist
        $this->setIsPlaylist(TRUE);

        # Assign the Playlist Items to a variable.
        $video_search=$yt->PlaylistItems($playlist_feed['id']);
        break;
    }
}

# If $video_search is not set then playlist does not exist.
if(!isset($video_search))
{
    return $display='That playlist doesn\'t exist. Please choose another.';
}

我有用于单个调用的代码,但我无法弄清楚如果播放列表 ID 不存在(来自下面的 YouTube 的结果)如何得到它返回的 404 错误。

YouTube 方法(PlaylistItems):

/**
 * PlaylistItems
 *
 * Retrieves videos from a playlist.
 *
 * @param   int $playlist_id            The ID of the playlist.
 * @param   string $part                The part parameter specifies a comma-separated list of
 *                                          one or more playlistItem resource properties that the API
 *                                          response will include. The part names that you can include
 *                                          in the parameter value are id, snippet, and contentDetails.
 * @access  public
 */
public function PlaylistItems($playlist_id, $part='snippet')
{
    # Set the Database instance to a variable.
    $doc=Document::getInstance();
    try
    {
        # Bring $youtube_service into the scope
        global $youtube_service;

        $playlistsItems_optParams=array('maxResults' => 50, 'playlistId' => $playlist_id);
        $playlistsItems=$youtube_service->playlistItems->listPlaylistItems($part, $playlistsItems_optParams);

        $new_array=$this->rebuildArray($playlistsItems, TRUE);

        # Instantiate a new Utility object.
        $utility=new Utility();
        # Sort the playlist array by date.
        $items=$utility->sortByDate($new_array, 'publishedAt');

        return $items;
    }
    catch(Exception $e)
    {
        # Print Results (below)
        print_r($e); exit;

        if($e->getCode()==404)
        {
            $doc->setError('That playlist doesn\'t exist. Please choose another.');
        }
    }
} #==== End -- PlaylistItems

单次调用代码:

# Playlist ID from URL
$playlist=$_GET['playlist'];

# Assign the Playlist Items to a variable.
$video_search=$yt->PlaylistItems($playlist);

PlaylistItems 方法返回

Google_ServiceException Object
(
    [errors:protected] => Array
        (
            [0] => Array
                (
                    [domain] => youtube.playlistItem
                    [reason] => playlistNotFound
                    [message] => Not Found
                    [locationType] => parameter
                    [location] => playlistId
                )

        )

    [message:protected] => Error calling GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLD2D6E64D9CD49E1&key=AIzaSyDVGJhk7DfKKJAaciX14aqyw_YbPaT4fp4: (404) Not Found
    [string:Exception:private] => 
    [code:protected] => 404
    [file:protected] => /Volumes/Coding/WebDev/CWIS/cwis.org/application/modules/Social/Google/io/Google_REST.php
    [line:protected] => 66
    [trace:Exception:private] => Array
        (
            [0] => Array
                (
                    [file] => /Volumes/Coding/WebDev/CWIS/cwis.org/application/modules/Social/Google/io/Google_REST.php
                    [line] => 36
                    [function] => decodeHttpResponse
                    [class] => Google_REST
                    [type] => ::
                    [args] => Array
                        (
                            [0] => Google_HttpRequest Object
                                (
                                    [batchHeaders:Google_HttpRequest:private] => Array
                                        (
                                            [Content-Type] => application/http
                                            [Content-Transfer-Encoding] => binary
                                            [MIME-Version] => 1.0
                                            [Content-Length] => 
                                        )

                                    [url:protected] => https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLD2D6E64D9CD49E1&key=AIzaSyDVGJhk7DfKKJAaciX14aqyw_YbPaT4fp4
                                    [requestMethod:protected] => GET
                                    [requestHeaders:protected] => Array
                                        (
                                        )

                                    [postBody:protected] => 
                                    [userAgent:protected] => google-api-php-client/0.6.0
                                    [responseHttpCode:protected] => 404
                                    [responseHeaders:protected] => Array
                                        (
                                            [content-type] => application/json; charset=UTF-8
                                            [date] => Thu, 18 Jul 2013 05:11:11 GMT
                                            [expires] => Thu, 18 Jul 2013 05:11:11 GMT
                                            [cache-control] => private, max-age=0
                                            [x-content-type-options] => nosniff
                                            [x-frame-options] => SAMEORIGIN
                                            [x-xss-protection] => 1; mode=block
                                            [server] => GSE
                                            [transfer-encoding] => chunked
                                        )

                                    [responseBody:protected] => {
 "error": {
  "errors": [
   {
    "domain": "youtube.playlistItem",
    "reason": "playlistNotFound",
    "message": "Not Found",
    "locationType": "parameter",
    "location": "playlistId"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}

                                    [accessKey] => 
                                )

                        )

                )

            [1] => Array
                (
                    [file] => /Volumes/Coding/WebDev/CWIS/cwis.org/application/modules/Social/Google/service/Google_ServiceResource.php
                    [line] => 186
                    [function] => execute
                    [class] => Google_REST
                    [type] => ::
                    [args] => Array
                        (
                            [0] => Google_HttpRequest Object
                                (
                                    [batchHeaders:Google_HttpRequest:private] => Array
                                        (
                                            [Content-Type] => application/http
                                            [Content-Transfer-Encoding] => binary
                                            [MIME-Version] => 1.0
                                            [Content-Length] => 
                                        )

                                    [url:protected] => https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLD2D6E64D9CD49E1&key=AIzaSyDVGJhk7DfKKJAaciX14aqyw_YbPaT4fp4
                                    [requestMethod:protected] => GET
                                    [requestHeaders:protected] => Array
                                        (
                                        )

                                    [postBody:protected] => 
                                    [userAgent:protected] => google-api-php-client/0.6.0
                                    [responseHttpCode:protected] => 404
                                    [responseHeaders:protected] => Array
                                        (
                                            [content-type] => application/json; charset=UTF-8
                                            [date] => Thu, 18 Jul 2013 05:11:11 GMT
                                            [expires] => Thu, 18 Jul 2013 05:11:11 GMT
                                            [cache-control] => private, max-age=0
                                            [x-content-type-options] => nosniff
                                            [x-frame-options] => SAMEORIGIN
                                            [x-xss-protection] => 1; mode=block
                                            [server] => GSE
                                            [transfer-encoding] => chunked
                                        )

                                    [responseBody:protected] => {
 "error": {
  "errors": [
   {
    "domain": "youtube.playlistItem",
    "reason": "playlistNotFound",
    "message": "Not Found",
    "locationType": "parameter",
    "location": "playlistId"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}

                                    [accessKey] => 
                                )

                        )

                )

            [2] => Array
                (
                    [file] => /Volumes/Coding/WebDev/CWIS/cwis.org/application/modules/Social/Google/contrib/Google_YoutubeService.php
                    [line] => 425
                    [function] => __call
                    [class] => Google_ServiceResource
                    [type] => ->
                    [args] => Array
                        (
                            [0] => list
                            [1] => Array
                                (
                                    [0] => Array
                                        (
                                            [part] => snippet
                                            [maxResults] => 50
                                            [playlistId] => PLD2D6E64D9CD49E1
                                        )

                                )

                        )

                )

            [3] => Array
                (
                    [file] => /Volumes/Coding/WebDev/CWIS/cwis.org/application/modules/Media/YouTube.php
                    [line] => 412
                    [function] => listPlaylistItems
                    [class] => Google_PlaylistItemsServiceResource
                    [type] => ->
                    [args] => Array
                        (
                            [0] => snippet
                            [1] => Array
                                (
                                    [maxResults] => 50
                                    [playlistId] => PLD2D6E64D9CD49E1
                                )

                        )

                )

            [4] => Array
                (
                    [file] => /Volumes/Coding/WebDev/CWIS/cwis.org/application/modules/Media/Video.php
                    [line] => 1130
                    [function] => PlaylistItems
                    [class] => YouTube
                    [type] => ->
                    [args] => Array
                        (
                            [0] => PLD2D6E64D9CD49E1
                        )

                )

            [5] => Array
                (
                    [file] => /Volumes/Coding/WebDev/CWIS/cwis.org/public/media/video/index.php
                    [line] => 59
                    [function] => displayVideoFeed
                    [class] => Video
                    [type] => ->
                    [args] => Array
                        (
                        )

                )

        )

    [previous:Exception:private] => 
)

如您所见,所有内容要么是protected,要么是private,所以我怎么知道是否有错误?

最佳答案

如果您使用的是 zend google api 库,则可以很容易地获取播放列表供稿,并捕获 google 将返回的任何错误(如果它不存在)。最简单的解决方案是获取帐户中所有播放列表的列表并循环查看播放列表 ID 是否与您拥有的 ID 匹配,然后从那里获取播放列表条目。这样就真的不会出现任何错误或异常。但是,那是您试图避免的多次通话。为了进行一次调用,您需要获得播放列表提要 url,然后进行一次调用并捕获异常。这些是我在处理 YouTube 播放列表时使用的几个函数的片段。

选项 1:

$this->api = new Zend_Gdata_YouTube();
$this->api->setMajorProtocolVersion(2);

$feed = $this->api->retrieveAllEntriesForFeed($this->api->getPlaylistListFeed('default'));
$playlistEntry = $this->__getPlaylistEntryFromFeed($feed, $playlistID);
//do what you want with the playlist entry, like get the list of all the videos




function __getPlaylistEntryFromFeed($feed, $entryId) {
    foreach($feed as $entry) {
       if($entry->getPlaylistId()->text == $entryId) {
        return $entry;
       }
    }
} 

选项 2:

try {
   $playlistVideoFeed = $this->api->getPlaylistVideoFeed($playlistFeedUrl. '?v=2&start-index=1');
   //this returns a list of videos in the playlist that you can loop through. see example function below.
} catch (Zend_Gdata_App_Exception $e) {
   echo $e->getMessage();
}


function getPlaylistVideos($playlistFeedUrl, $start=1, $total=0, $videos = array()) {
        $playlistVideoFeed = $this->api->getPlaylistVideoFeed($playlistFeedUrl. '?v=2&start-index='.$start);

        foreach ($playlistVideoFeed as $videoEntry) {
            $videos[] = $this->getDataFromVideoEntry($videoEntry);
        }
        $count = count($playlistVideoFeed);

        if(count($videos) < $total && $count != 0) {
            $videos = $this->getPlaylistvideos($playlistFeedUrl, $start + ($count-1), $total, $videos);
        }
        return $videos;
    }

要获取这些示例并将它们与您的代码一起使用,您可以尝试看起来像这样:

# Playlist ID from URL
$playlist=$_GET['playlist'];

# Assign the Playlist Items to a variable.
$video_search;
try {
    $video_search = $yt->PlaylistItems($playlist);
} catch(Google_ServiceException $e) {
   //there was an error
   echo $e->getMessage();
}

希望对您有所帮助。

关于php - YouTube API v3 : How to get returned 404 (not found) error from PlaylistItems?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733258/

相关文章:

Php Storm "Test framework quit unexpectedly"

php - 文本魔术短信 API 在 Godaddy 共享主机上出现错误

php - PHP YouTube API视频标题解析

youtube - YouTube API搜索/列表为空的代码段描述

php - 通过特定值的最大值从多维数组返回值

php - 尝试更新时 PDO 更新错误

php - 出现错误 '#1111 - Invalid use of group function'

python - 如何在python脚本中从youtube-dl中提取文件大小?

youtube - 您可以从一个刷新/访问 token 返回多个 channel 吗?

javascript - 如何使用 jQuery 禁用/启用 YouTube 视频上的播放按钮?