【发布时间】:2015-10-03 16:40:04
【问题描述】:
我想使用新的 API v3 从我的 youtube 频道获取订阅者数量。
- 我在这里为 youtube 创建了一个 Google API 应用程序:Google API Console
- 我有 APP 密钥和 youtube 频道 ID
- 我使用“json_decode”来获取对象
<?php
$url_yt = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNELID&key=APIKEY";
$yt_array = file_get_contents($url_yt);
$ytcount = json_decode($yt_array, true);
$ytsubscribers = $ytcount['items'][0]['subscriberCount'];
echo $ytsubscribers;
?>
即使代码 sn-p 看起来没问题,我也会遇到一些错误。
Warning: file_get_contents() [function.file-get-contents]: SSL: Success in /ytsub2.php on line 4
Warning: file_get_contents() [function.file-get-contents]: Failed to enable crypto in /ytsub2.php on line 4
Warning: file_get_contents(https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNELID&key=APIKEY) [function.file-get-contents]: failed to open stream: operation failed in /ytsub2.php on line 4
我不知道如何解决这个错误。我的站点服务器似乎无法正确获取 JSON。
编辑:
我尝试使用 cURL 没有任何结果:
<?php
//function to get the remote data
function url_get_contents ($url) {
if (function_exists('curl_exec')){
$conn = curl_init($url);
curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($conn, CURLOPT_FRESH_CONNECT, true);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
$url_get_contents_data = (curl_exec($conn));
curl_close($conn);
}elseif(function_exists('file_get_contents')){
$url_get_contents_data = file_get_contents($url);
}elseif(function_exists('fopen') && function_exists('stream_get_contents')){
$handle = fopen ($url, "r");
$url_get_contents_data = stream_get_contents($handle);
}else{
$url_get_contents_data = false;
}
return $url_get_contents_data;
}
$url_yt = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNELID&key=APIKEY";
$yt_array = url_get_contents($url_yt);
$ytcount = json_decode($yt_array, true);
$ytsubscribers = $ytcount['items'][0]['subscriberCount'];
// echo the youtube follower count
echo $ytsubscribers;
?>
【问题讨论】:
-
这是你的文件
ytsub2.php?如果是这样,我们能看到整个事情吗? -
@jonmrich 这个 php 页面只包含将关注者数显示为测试页面的代码。
-
@cmorrissey 刚刚尝试使用 cURL,但我没有得到任何结果。请检查我的帖子编辑。谢谢
-
你最后做对了吗?如果是,我需要那个代码!谢谢!
标签: php json youtube-api