PinoyStackOverflower
PinoyStackOverflower

Reputation: 5302

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! :)

Upvotes: 4

Views: 10455

Answers (3)

Anoop P S
Anoop P S

Reputation: 782

This link provides the youtube channel report in range. But when used with google php library it get hooked in a "User login required Error!"

https://developers.google.com/apis-explorer/#p/youtubeAnalytics/v1/youtubeAnalytics.reports.query?ids=channel%253D%253DMINE&start-date=2014-05-01&end-date=2014-06-30&metrics=views&dimensions=day&_h=3&

Is there any way i can access the channel analytics report in youtube V3 same as like in v3

http://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.list?part=statistics&id=UCMGgBRBiijmpgL3xNuiDVOQ&_h=10&

Upvotes: 0

anish
anish

Reputation: 7412

  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

Upvotes: 2

mpgn
mpgn

Reputation: 7241

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;
    }
}

Upvotes: 10

Related Questions