如何获取 PHP 的 YT 视频的观看次数?

How to get the view count of a YT video with PHP?

我有以下代码:

<?php   
    $id = 'bsTY5cTi3nI';
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" . $id . "&key=...");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{"entry"}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>

我想获取 PHP 的 YT 视频的观看次数。但是我收到以下错误消息:

Notice: Undefined property: stdClass::$entry in D:\XAMPP\htdocs\Project1\WatchToGether\test2.php on line 5
Notice: Trying to get property 'yt$statistics' of non-object in D:\XAMPP\htdocs\Project1\WatchToGether\test2.php on line 5
Notice: Trying to get property 'viewCount' of non-object in D:\XAMPP\htdocs\Project1\WatchToGether\test2.php on line 5

有人可以帮我解决我的问题吗?我将不胜感激。

您正在从 video 资源中寻找 statistics 对象。你可以这样获取:

<?php

$id = 'bsTY5cTi3nI';
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $id . "&key=...");

$JSON_Data = json_decode($JSON);
$views = $JSON_Data->items[0]->statistics->viewCount;
echo $views; // 264447