Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTube API v3 PHP get total number of views in a channel

I would like to know how to get the total number of channel views. I've been searching all over the youtube API, but can't seem to find one.

Your help will be greatly appreciated.

Thanks! :)

like image 984
PinoyStackOverflower Avatar asked Dec 19 '22 11:12

PinoyStackOverflower


2 Answers

You need to use Channel.list of the API. The total view of a channel is in the part statistics.

You need the channel name or the channel id. If you want the channel id but you only have the channel name, you can use this app to get the YouTube Id of the channel.

The result form is :

{
 "kind": "youtube#channelListResponse",
 "etag": "\"gMjDJfS6nsym0T-NKCXALC_u_rM/0FiX4yi2JggRgndNH8LVUqGkBEs\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {

   "kind": "youtube#channel",
   "etag": "\"gMjDJfS6nsym0T-NKCXALC_u_rM/ch89JvwOeEbWio2fOHY7sxE7XCc\"",
   "id": "UCMGgBRBiijmpgL3xNuiDVOQ",
   "statistics": {
    "viewCount": "5861117",
    "commentCount": "275",
    "subscriberCount": "40674",
    "hiddenSubscriberCount": false,
    "videoCount": "29"
   }
  }
 ]
}

The total view of the channel is in the part [items"][0]["statistics"]["viewCount"]

For this channel, the viewCount is : 5 861 117, the same number if you look at the channel https://www.youtube.com/user/Vecci87/about.

LIVE EXAMPLE

EDIT

You can use Youtube API Analytics. Important information, you need to be the owner of the YouTube Account, this method requires authenfification with Oauth2. I made you a basic example, I define two date : today and a past day. I set the metrics to view and a dimension to day, to have the view for each days. Finally i add all this values.

$today = date("Y-m-d");
$datePast = date('Y-m-d', strtotime("-".$period." day"));
try {
    $activitiesView = $youtube->reports->query('channel=='.$idde.'', $datePast , $today, 'views', array('dimensions' => 'day'));
} catch(Google_ServiceException $e) { }

$average = 0;
if(isset($activitiesView['rows'])) {
    foreach ($activitiesView['rows'] as $value) {
        $average += $value[1];
    }   
    $average = $average/count($activitiesView['rows']);
}

Full code example :

<?php

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_YouTubeAnalyticsService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';

// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();

$client = new Google_Client();
$client->setApplicationName('Google+ PHP Starter Application');

$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setDeveloperKey('YOUR_DEV_KEY');

$youtube = new Google_YouTubeAnalyticsService($client);
$service = new Google_YouTubeService($client);
$auth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));  
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {

    /***************USER STATS********************/
    $today = date("Y-m-d");
    $datePast = date('Y-m-d', strtotime("-".$period." day"));
    try {
        $activitiesView = $youtube->reports->query('channel=='.$idde.'', $datePast , $today, 'views', array('dimensions' => 'day'));
    } catch(Google_ServiceException $e) { }

    $average = 0;
    if(isset($activitiesView['rows'])) {
        foreach ($activitiesView['rows'] as $value) {
            $average += $value[1];
        }   
        $average = $average/count($activitiesView['rows']);
    }


    /***************USER STATS********************/

  $_SESSION['token'] = $client->getAccessToken();
} else {

    $authUrl = $client->createAuthUrl();
    //simple verification
    if(strpos($RedirectUri, "redirect_uri") !== false) {
        header('Location: error.php');
        exit;
    }
}
like image 168
mpgn Avatar answered Dec 22 '22 03:12

mpgn


  1. Go to the Following URL

https://developers.google.com/youtube/v3/docs/channels/list

  1. Use the API Explorer to call this method on live data and see the API request and response Sample Images
  2. Execute the API and see the response

enter image description here

  1. View the Statistics Section there you can find the information what you are looking for
like image 20
anish Avatar answered Dec 22 '22 02:12

anish