Using YouTube Data API v3 to get a channel’s subscribers and lifetime views

One of the requirements of the Influencer Relationship Management System was to provide the functionality to automatically update the reach a YouTube channel subscribers and lifetime views. That was achieved by using YouTube Data API v3, which provides access to video statistics and YouTube channels’ data.

The way it works is by submitting an API request to pull data from a specific channel which is retrieved in a JSON format. The publicly available data containing the subscribers and lifetime views values is then contained in the response.

Here is the php script that submits the request, decodes the response and displays the integer values of the required variables.

<?php

// Authentication
$api_key = "registered_api_key_here";

// Chanel ID (National Geographic)
$chann_id = "UCpVm7bg6pXKo1Pr6k5kxG9A";
    
//reading the channel file containing required data in JSON format
$subscribers = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id='.$chann_id.'&key='.$api_key);
$views = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=statistics&id='.$chann_id.'&key='.$api_key);

// Decoding the JSON string and converting it into PHP variables.
$response = json_decode($subscribers, true );
$response2 = json_decode($views, true );

// Getting the integer value from the variables of Subscribers and Lifetime views 
$subscribersCount = intval($response['items'][0]['statistics']['subscriberCount']);
$viewsCount = intval($response2['items'][0]['statistics']['viewCount']);  
 
?>

The JSON response looked like this:

{
 "kind": "youtube#channelListResponse",
 "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/1zEOkGDS0kY4pSZNROiArXCqjbw\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#channel",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/vsaG5hJrv8E1XG2XRqam3bReoWQ\"",
   "id": "UCpVm7bg6pXKo1Pr6k5kxG9A",
   "statistics": {
    "viewCount": "1883246472",
    "commentCount": "569",
    "subscriberCount": "6120428",
    "hiddenSubscriberCount": false,
    "videoCount": "7988"
   }
  }
 ]
}

On each page refresh, an updated values of the used channel’s subscribers and lifetime were pulled.
Demo: Here

That was the first testing step in making the script which would meet the requirement mentioned above. More details on the upgraded version Here

Useful Sources:
YouTube Data API v3
JSON
Filesystem Functions
JSON Functions
Variable handling Functions

Share this Post

One Comment on “Using YouTube Data API v3 to get a channel’s subscribers and lifetime views”

Leave a Reply

Your email address will not be published. Required fields are marked *