Laurent Laurent - 6 months ago 140
JSON Question

Grabbing the current viewer count for youtube live streaming

I am looking to display the current viewer count for youtube live streams, i can do this for youtube video with this code :

<?php
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?
part=statistics&id=videiID&key=APIKey");
$json_data = json_decode($JSON, true);
echo $json_data['items'][0]['statistics']['viewCount'];
?>


but this not display the current viewers count !

Answer

Try this link: https://www.youtube.com/live_stats?v={videoid}

Find a Live event on YouTube and replace the video id in the link. This should retrieve the number of concurrent views for that particular video.

If so, refresh the page and compare the number with the concurrent viewers on the YouTube page.

UPDATE:


Here is an example of how you can add it to your website. You can set up a php file and a html file.

viewers.php:

<?php
$viewers = file_get_contents('https://www.youtube.com/live_stats?v=y60wDzZt8yg');
echo $viewers;
?>

viewers.html:

<html>
<body>
<div id="status" style="color: #666; line-height: 24px; font-size: 19px; font-weight: normal; font: 19px Roboto,arial,sans-serif;"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var statusIntervalId = window.setInterval(update, 5000);
function update() {
$.ajax({
    url: 'viewers.php',
    dataType: 'text',
    success: function(data) {
        if (parseInt(data) == 0) {
            $("#status").css({ display: "none" });
        } else {
            $("#status").text(parseInt(data) + ' watching now' );
        }
    }
})
}
</script>
</body>
</html>

As you can see, I use the PHP file to retrieve the data from YouTube using the live_stats link. I then use the HTML with jquery to update the data dynamically every 5 seconds.

<div id="status"... is where the data is shown and styled with a bit of css.
<script src="... is where the jQuery library is loaded.
<script type="... is where jQuery retrieves data from the PHP file and displays it in the first div or hides it if there are 0 viewers.

If so, you can modify and embed this code anywhere inside a webpage or you can load it through an iframe which is not recommended though.

Here is an image of it working for me:
enter image description here