如何在 PHP 中使用 YouTube API 获取 YouTube 中的视频总数


How to get total videos in YouTube with YouTube API in PHP

我有PHP代码来获取YouTube视频中的观看次数:

$xdoc = new DomDocument;
$xdoc->Load('http://gdata.youtube.com/feeds/api/users/myUserName');
$ytstat = $xdoc->getElementsByTagName('statistics')->item(0);
$total_views = $ytstat->getAttribute(totalUploadViews);

现在如何获得上传的视频总数?感谢您的帮助。

您当然更喜欢使用 YouTube API v2 的 JSON 格式:

<?php
$username = 'username';
$user = json_decode(file_get_contents(
    "https://gdata.youtube.com/feeds/api/users/$username?v=2&alt=json"));
$uploads = json_decode(file_get_contents(
    "https://gdata.youtube.com/feeds/api/users/$username/uploads?v=2&alt=jsonc&max-results=0"));
printf("Total uploads: %d'nTotal views: %d'n",
    $uploads->data->totalItems,
    $user->entry->{'yt$statistics'}->totalUploadViews);

更好的是,您可能希望使用新的 YouTube API v3,该 API v3 会在单个请求中报告这两个信息。要使用新的API,您必须在Google Cloud Console上获取API密钥,并进一步启用YouTube Data API v3。以下是 YouTube API v3 代码:

<?php
$username = 'username';
$api_key = 'your-api-key';
$channel = json_decode(file_get_contents(
    "https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=$username&key=$api_key"));
printf("Total uploads: %d'nTotal views: %d'n",
    $channel->items->statistics->videoCount,
    $channel->items->statistics->viewCount);

更多信息:

  • YouTube API 参考 3.0
  • YouTube API 参考指南 2.0