ljn
ljn

Reputation: 27

How to get total videos in YouTube with YouTube API in PHP

i've got the PHP codes to get number of views in my YouTube videos:

$xdoc = new DomDocument;
$xdoc->Load('http://gdata.youtube.com/feeds/api/users/myUserName');
$ytstat = $xdoc->getElementsByTagName('statistics')->item(0);
$total_views = $ytstat->getAttribute(totalUploadViews);

Now how to get total uploaded videos? Thanks for helps.

Upvotes: 0

Views: 2513

Answers (1)

Paulo Freitas
Paulo Freitas

Reputation: 13649

You certainly will prefer to use the JSON format of YouTube API v2:

<?php

$username = 'username';
$user = json_decode(file_get_contents(
    "https://gdata.youtube.com/feeds/api/users/$username?v=2&alt=json"));
$uploads = json_decode(file_get_contents(
    "https://gdata.youtube.com/feeds/api/users/$username/uploads?v=2&alt=jsonc&max-results=0"));
printf("Total uploads: %d\nTotal views: %d\n",
    $uploads->data->totalItems,
    $user->entry->{'yt$statistics'}->totalUploadViews);

Even better, you might want to use the new YouTube API v3 which reports both info in a single request. To use the new API you'll have to get an API key on Google Cloud Console and further enable the YouTube Data API v3. Here's the YouTube API v3 code:

<?php

$username = 'username';
$api_key = 'your-api-key';
$channel = json_decode(file_get_contents(
    "https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=$username&key=$api_key"));
printf("Total uploads: %d\nTotal views: %d\n",
    $channel->items->statistics->videoCount,
    $channel->items->statistics->viewCount);

Further info:

Upvotes: 1

Related Questions