I want to get the subscriber count from my youtube channel with the new API v3.
- I created a Google API app for youtube here: Google API Console
- I have both the APP key and the youtube channel ID
- I use "json_decode" to get the object
<?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;
?>
I get some errors even if the code snippet looks ok.
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
I have no idea how to fix this errors. It seems my site server is not able to get the JSON properly.
EDIT:
I tried using cURL without any result:
<?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;
?>