【发布时间】:2020-01-02 14:01:28
【问题描述】:
我创建了这个 PHP 脚本,它从 youtube 频道打印出指定数量的最新 youtube 视频。我将 maxResults 设置为 10,但它返回数百个结果。请通过代码和帮助。
<?php
$API_Url = 'https://www.googleapis.com/youtube/v3/';
$API_Key = '...';
$channelId = 'UCX6OQ3DkcsbYNE6H8uQQuVA';
$parameter = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $API_Key
];
$channel_URL = $API_Url . 'channels?' . http_build_query($parameter);
$json_details = json_decode(file_get_contents($channel_URL), true);
$playlist=$json_details['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$parameter = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> 10,
'key'=> $API_Key
];
$channel_URL = $API_Url . 'playlistItems?' . http_build_query($parameter);
$json_details = json_decode(file_get_contents($channel_URL), true);
$my_videos = [];
foreach($json_details['items'] as $video){
//$my_videos[] = $video['snippet']['resourceId']['videoId'];
$my_videos[] = array( 'v_id'=>$video['snippet']['resourceId']['videoId'], 'v_name'=>$video['snippet']['title'] );
}
while(isset($json_details['nextPageToken'])){
$nxt_page_URL = $channel_URL . '&pageToken=' . $json_details['nextPageToken'];
$json_details = json_decode(file_get_contents($nxt_page_URL), true);
foreach($json_details['items'] as $video)
$my_videos[] = $video['snippet']['resourceId']['videoId'];
}
print_r($my_videos);
//foreach($my_videos as $video){
//if(isset($video)){
//echo '<a href="https://www.youtube.com/watch?v='. $video['v_id'] .'">
//<div>'. $video['v_name'] .'</div>
//</a><br><br><br>';
//}
//}
而且它返回的额外结果甚至没有标题或 ID。自己看图
【问题讨论】:
-
您的循环似乎不断获得更多结果,所以您是否预计会有超过 10 个结果?这段代码是你写的吗?
-
不是全部...我遵循了 youtube 教程
-
好的,那能回答你的问题吗?以
while(isset($json_details['nextPageToken'])){开头的块获取下一页,然后是之后的页面并继续执行,直到每次将视频 ID 添加到$my_videos时,API 都不会在响应中返回nextPageToken参数。 -
据我说,循环是无关紧要的。 api 已经在发送所有这些结果。
-
好的。那么您建议进行哪些更改
标签: php youtube youtube-api youtube-data-api