YouTube Data API按日期获取频道视频列表异常求助
问题描述
我调用YouTube Data API获取频道最新视频,但不管是代码运行还是在YouTube测试平台,只能正确获取最新4个视频,后续返回的都是旧视频,缺失了2024年4月发布的其他视频。
我的代码:
$video_list = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&type=video&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.'')); $json = '['; $i = 0; foreach ($video_list->items as $item) { if($i > 0){ $json .= ','; } $json .= ' { "videoId": "'. $item->id->videoId .'", "url": "https://www.youtube.com/watch?v='. $item->id->videoId .'", "title": "'. $item->snippet->title .'", "description": "'. $item->snippet->description .'", "thumbnail": "https://i.ytimg.com/vi/'. $item->id->videoId .'/hqdefault.jpg", "publishedAt": "'. $item->snippet->publishedAt .'" }'; $i++; } $json .= ']'; //echo fJson($json); file_put_contents('youtube.json', fJson($json));
返回结果示例:
[ { "videoId": "fSvy6ZHM2vY", "title": "Terre de sports - le showdown un sport meéconnu destiné aux non voyants", "description": "Lointain cousin du tennis de table et du air hockey, le showdown est un sport étonnant qui commence à trouver de nombreux ...", "publishedAt": "2024-04-17T06:46:23Z" }, { "videoId": "wgG-SaK3KyM", "title": "RECETTE GAGNANTE POUR LES BURGERS SOLIDAIRES DU DÉPARTEMENT", "description": "Lundi 15 avril, le Président de la Seine-Maritime, Bertrand Bellanger a officialisé la distribution de la recette de l'opération “burger ...", "publishedAt": "2024-04-17T06:35:55Z" }, { "videoId": "kjzcF7hFTDE", "title": "Carnet d'expos - La beauté cachée des graines", "description": "Elles sont symboles de vie, de croissance, de diversité et de culture aussi. Des graines de toutes sortes sont passées sous ...", "publishedAt": "2024-04-15T13:52:36Z" }, { "videoId": "zGvn6VJWu5E", "title": "L'abbaye Saint-Georges, une plongée dans des jardins monastiques", "description": "Ces jardins vivriers labellisés « jardin remarquable » avec leur potager, leurs plantes médicinales et leurs fruitiers ont été ...", "publishedAt": "2024-04-12T13:15:04Z" }, { "videoId": "wrJAjhXGdAw", "title": "BOUJOU LA SEINE - Les insolites d'Ariane Au Genetey, un manoir de légendes", "description": "Au Genetey, un manoir de légendes : C'est un lieu chargé d'histoires, blotti au fond d'une impasse, en lisière de forêt.", "publishedAt": "2023-07-15T06:00:18Z" }, { "videoId": "KFoMkpi4KqA", "title": "BOUJOU LA SEINE - Les insolites d'Ariane - la nature a trouvé son refuge", "description": "À Heurteauville, une ancienne tourbière cache un trésor de biodiversité. Le lieu, classé Espace Naturel Sensible est aujourd'hui ...", "publishedAt": "2023-07-08T06:00:12Z" }, ... ]
问题分析与解决方案
核心原因
你使用的Search.list接口存在自动去重/相似内容过滤机制:当频道内存在主题、格式高度相似的批量上传视频时,YouTube会将这些视频合并展示,只保留最新的几个,导致后续返回旧视频,无法获取完整的最新视频列表。
解决方案:改用频道上传列表API
每个YouTube频道都有一个默认的「上传」播放列表,通过Channels.list接口获取该播放列表ID,再用PlaylistItems.list接口遍历这个列表,就能拿到所有公开上传的视频,不会被过滤。
修改后的代码
// 第一步:获取频道的上传播放列表ID $channel_response = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id='.$channelID.'&key='.$API_key.'')); $upload_playlist_id = $channel_response->items[0]->contentDetails->relatedPlaylists->uploads; $all_videos = []; $next_page_token = ''; // 第二步:分页获取播放列表中的所有视频(处理分页,maxResults最大为50) do { $playlist_url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId='.$upload_playlist_id.'&order=date&maxResults=50&pageToken='.$next_page_token.'&key='.$API_key.''; $playlist_response = json_decode(file_get_contents($playlist_url)); foreach ($playlist_response->items as $item) { $all_videos[] = [ 'videoId' => $item->snippet->resourceId->videoId, 'url' => 'https://www.youtube.com/watch?v='.$item->snippet->resourceId->videoId, 'title' => $item->snippet->title, 'description' => $item->snippet->description, 'thumbnail' => $item->snippet->thumbnails->high->url, // 用high分辨率缩略图,也可以换hqdefault 'publishedAt' => $item->snippet->publishedAt ]; } $next_page_token = isset($playlist_response->nextPageToken) ? $playlist_response->nextPageToken : ''; } while ($next_page_token !== ''); // 生成JSON并保存 $json = json_encode($all_videos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); file_put_contents('youtube.json', $json);
代码说明
- 获取上传列表ID:通过
Channels.list接口的contentDetails部分,拿到频道专属的上传播放列表ID。 - 分页遍历视频:
PlaylistItems.list接口最多一次返回50条数据,通过nextPageToken循环获取所有页面的视频,直到没有下一页。 - 避免手动拼接JSON:使用
json_encode自动生成合法JSON,避免手动拼接的语法错误。
内容的提问来源于stack exchange,提问作者Baptiste Dumouchel
相关产品推荐
相关产品推荐

