您当然会更喜欢使用 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,您必须在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);
更多信息: