如何使用php的youtube API知道频道的订阅者数量?

时间:2019-09-06 21:10:20

标签: youtube-api

我正在尝试将YouTube订阅服务器计数器放置在我的网站上。但是我不知道使用YouTube v3 API时php中的代码是什么。

1 个答案:

答案 0 :(得分:0)

获取API密钥(如果没有): https://developers.google.com/youtube/v3/getting-started

您将需要频道ID(可以从URL获取): https://www.youtube.com/channel/ {channel_id}

这是一个使用file_get_contents的简单PHP程序:

<?php

$apiKey = 'YOUR_API_KEY';

//https://www.youtube.com/channel/{channel_id}
$channel_id = 'UC8butISFwT-Wl7EV0hUK0BQ';

$response = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id='. $channel_id .'&key='. $apiKey);

$data = json_decode($response);

$subscriber_count = $data->items[0]->statistics->subscriberCount;

echo $subscriber_count;

注意:您可以通过添加错误处理来改进它。如果可以的话,还可以使用curl或Guzzle之类的库来代替file_get_contents。

您可以在此处了解有关渠道资源的更多信息: https://developers.google.com/youtube/v3/docs/channels