D
D
dojdimon2014-07-06 18:43:39
YouTube
dojdimon, 2014-07-06 18:43:39

How to sum views of all videos in a Youtube playlist?

https://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json

We need to take the value of each viewCount in the playlist and sum them up. Playlists can be of any length. I'm trying to do it like this:
<?php
$youtube_view_count = json_decode(file_get_contents('https://gdata.youtube.com/feeds/api/playlists/PL7FC6D85A4AE63E21'))->entry->{'yt:statistics'}->viewCount;

$elem = new SimpleXMLElement($youtube_view_count);
$a = viewCount;
foreach ($elem as $a){ 
printf($a->count());
}
?>

But nothing comes out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladlen Grachev, 2014-07-06
@dojdimon

You get JSON, and then you try to parse it all as XML. That's why it doesn't come out.
A bit of a crutch, but something like this:

$playlist = file_get_contents('https://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json');
$playlist = str_replace('yt$statistics', 'yt_statistics', $playlist);
$playlist = json_decode($playlist);
$entries = $playlist->feed->entry;
$views = 0;
foreach ((array)$entries as $entry) {
  $views += $entry->yt_statistics->viewCount;
}
echo $views;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question