2015-07-14 6 views
3

Я хочу получить счет подписчика с моего канала YouTube с новым API v3.Подбор подписчиков YouTube с помощью нового API YouTube v3

  1. Я создал приложение API Google для YouTube здесь: Google API Console
  2. У меня есть и ключ APP и канал YouTube ID
  3. Я использую "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; 
 
?>

я получаю некоторые ошибки, даже если фрагмент кода выглядит нормально.

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. заранее спасибо за вашу помощь

EDIT:

Я попытался с помощью Curl без результата:

<?php 
 

 
\t //function to get the remote data 
 
\t function url_get_contents ($url) { 
 
\t  if (function_exists('curl_exec')){ 
 
\t   $conn = curl_init($url); 
 
\t   curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true); 
 
\t   curl_setopt($conn, CURLOPT_FRESH_CONNECT, true); 
 
\t   curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1); 
 
\t   $url_get_contents_data = (curl_exec($conn)); 
 
\t   curl_close($conn); 
 
\t  }elseif(function_exists('file_get_contents')){ 
 
\t   $url_get_contents_data = file_get_contents($url); 
 
\t  }elseif(function_exists('fopen') && function_exists('stream_get_contents')){ 
 
\t   $handle = fopen ($url, "r"); 
 
\t   $url_get_contents_data = stream_get_contents($handle); 
 
\t  }else{ 
 
\t   $url_get_contents_data = false; 
 
\t  } 
 
\t return $url_get_contents_data; 
 
\t } 
 
\t 
 

 

 
\t $url_yt = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNELID&key=APIKEY"; 
 
\t $yt_array = url_get_contents($url_yt); 
 
\t $ytcount = json_decode($yt_array, true); 
 
\t $ytsubscribers = $ytcount['items'][0]['subscriberCount']; 
 

 

 

 
// echo the youtube follower count 
 
    echo $ytsubscribers; 
 

 
?>

+0

Является ли это ваш файл 'ytsub2.php'? Можем ли мы увидеть все это, если так? – jonmrich

+0

http://stackoverflow.com/questions/1975461/how-to-get-file-get-contents-work-with-https – cmorrissey

+0

@jonmrich Эта страница php содержит только код для отображения followercount в качестве тестовой страницы. –

ответ

0

Убедитесь, что вы позволяете доступ с вашего IP-адреса в Google Developers Console.

Кроме того, измените эту строку:

$ytsubscribers = $ytcount['items'][0]['subscriberCount']; 

к этому:

$ytsubscribers = $ytcount['items'][0]['statistics']['subscriberCount']; 
+0

Спасибо. В Google Dev Console каждый URL-адрес разрешен для этого API. Вы правы, «$ ytsubscribers» фиксируется в соответствии с тем, что вы сказали. Но он все еще ничего не отображает. –

1

Вот правильный рабочий код с Curl:

\t # url_get_contents function by Andy Langton: http://andylangton.co.uk/ 
 
\t function url_get_contents($url,$useragent='cURL',$headers=false, $follow_redirects=false,$debug=false) { 
 
\t # initialise the CURL library 
 
\t $ch = curl_init(); 
 
\t # specify the URL to be retrieved 
 
\t curl_setopt($ch, CURLOPT_URL,$url); 
 
\t # we want to get the contents of the URL and store it in a variable 
 
\t curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
 
\t # specify the useragent: this is a required courtesy to site owners 
 
\t curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
 
\t # ignore SSL errors 
 
\t curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
 
\t # return headers as requested 
 
\t if ($headers==true){ 
 
\t curl_setopt($ch, CURLOPT_HEADER,1); 
 
\t } 
 
\t # only return headers 
 
\t if ($headers=='headers only') { 
 
\t curl_setopt($ch, CURLOPT_NOBODY ,1); 
 
\t } 
 
\t # follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up 
 
\t if ($follow_redirects==true) { 
 
\t curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
 
\t } 
 
\t # if debugging, return an array with CURL's debug info and the URL contents 
 
\t if ($debug==true) { 
 
\t $result['contents']=curl_exec($ch); 
 
\t $result['info']=curl_getinfo($ch); 
 
\t } 
 
\t # otherwise just return the contents as a variable 
 
\t else $result=curl_exec($ch); 
 
\t # free resources 
 
\t curl_close($ch); 
 
\t # send back the data 
 
\t return $result; 
 
\t } 
 
    
 
    \t $url_yt = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=YOUR_CHANNEL_ID&key=YOUR_API_KEY"; 
 
\t url_get_contents($url_yt); 
 
\t $yt_array = url_get_contents($url_yt); 
 
\t $ytcount = json_decode($yt_array, true); 
 
\t $ytsubscribers = $ytcount['items'][0]['statistics']['subscriberCount'];

Затем вызовите переменную $ ytsubscribers, где вы хотите ее отобразить.

echo $ytsubscribers;

Смежные вопросы