How to get youtube subscribers count in php

Rakesh Sharma      1 Comment  

How to get youtube subscribers count in php and wordpress using api v3.0

Today i am working with youtube api to get youtube subscribers count. Then i found The YouTube API v2.0 is deprecated. And 3.0 has been released so no need to oauth with this api version. We need to just need an API KEY to get work. Let’s see how to get youtube subscribers count in php and wordpress using api v3.0. Below i am shring all the steps to get api key and get subscribers count.

How to get youtube api key

:- Below are the steps to get youtube api key
1. Go to https://console.developers.google.com/. And log in to your google account.

2. Navigate to “APIs & auth” and click on “APIs”.
3. Now click on “YouTube Data API” link under “YouTube APIs”. And click on “Enable API” Button.
4. Now your youtube api has been enabled for your project. Now click on “credentials” under “APIs & auth”.

How to get youtube subscribers count in php

5. Click on “Add Credentials” Then “API key” in dropdown.

How to get youtube subscribers count in php part

6. Now a new popup window will appear, click on “Browser key” button. Then fill your url if any else click on “Create Key” button.

youtube3

7. A new popup window will appear which showing your “API key”. Copy and use this key to get subscribers count.

How to get youtube subscribers count in php

There are curl and file_get_contents() methods in php to get remote contents. Below we are calling youtube api to get subscribers count. Change YOUR_CHANNEL_ID and YOUR_API_KEY with yours.

// Calling api.
$subscribers = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=YOUR_CHANNEL_ID&key=YOUR_API_KEY');
// Decoding json response
$response = json_decode($subscribers, true );
// echoing subscribers count.
echo $count = intval($response['items'][0]['statistics']['subscriberCount']);

How to get youtube subscribers count in wordpress

There are wp_remote_get() method in wordpress to get remote contents. Below we are calling youtube api to get subscribers count. Change YOUR_CHANNEL_ID and YOUR_API_KEY with yours.

$params = array('sslverify' => false,'timeout' => 60);
$yt_data = wp_remote_get('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=YOUR_CHANNEL_ID&key=YOUR_API_KEY', $params);
if (is_wp_error($yt_data) || '400' <= $yt_data['response']['code'] ) {
  echo 'Something went wrong';
} 
else {
  $response = json_decode( $yt_data['body'], true );
 echo $count = intval($response['items'][0]['statistics']['subscriberCount']);
}

So now you can easily get your youtube subscribers count in php and wordpress using api v3.0.

  • Isa

    Hi! How can I get suscribers count from any channel? Not only my channel?