skip to Main Content

I want to display view count of a youtube video in a website. The below code is written for it. But it does not print the view count, only shows the youtube video.

Here is my code,

`<!DOCTYPE html>
<html>
<head>
    <title>How to put PHP in HTML - Simple Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        function videoViews() {
            var rex = /[a-zA-Z0-9-_]{11}/,
            videoUrl = $('input').val() === '' ? alert('Enter a valid Url'):$('input').val(),
            videoId = videoUrl.match(rex),
            jsonUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json',
            embedUrl = '//www.youtube.com/embed/' + videoId,
            embedCode = '<iframe width="350" height="197" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>';
    
            //Get Views from JSON
            $.getJSON(jsonUrl, function (videoData) {
                var videoJson = JSON.stringify(videoData),
                vidJson = JSON.parse(videoJson),
                views = vidJson.entry.yt$statistics.viewCount;
                $('.views').text(views);
            });
    
            //Embed Video
            $('.videoembed').html(embedCode);
        }
    </script>
</head>
<body>
    <input type="url" placeholder="Enter Youtube video URL"> 
    <a href="#" onClick="videoViews()">GO</a>
    
    <div class="videoembed"></div>
    <div class="views"></div>

    <?php
    if(isset($_GET['url'])) {
        $video_ID = substr($_GET['url'], -11);
        $JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id={$video_ID}&key=AIzaSyAGquK-QPs8yaddEqhL1AEmYbrJKT6xs04");
        $JSON_Data = json_decode($JSON);
        $views = $JSON_Data->items[0]->statistics->viewCount;
        echo "<script>$('.views').text($views);</script>";
    }
    ?>
</body>
</html>`

I want to display Number of Views of a given video in my website.

2

Answers


  1. In your JavaScript code, you are using the YouTube Data API to get the view count for a YouTube video and update the .views element with that count. However, in your PHP code, you are trying to do the same thing using a different API endpoint.

    To fix the issue and display the view count using the YouTube Data API, you can remove the PHP code and update your JavaScript code as follows:

    1. Replace the existing jsonUrl variable with the following:
    var jsonUrl = 'https://www.googleapis.com/youtube/v3/videos?id=' + videoId + '&part=statistics&key=YOUR_API_KEY';
    

    Replace YOUR_API_KEY with your own YouTube Data API key.

    1. Update the $.getJSON function to handle the API response and update the view count on the page. Replace the existing $.getJSON function with the following:
    $.getJSON(jsonUrl, function (data) {
        var views = data.items[0].statistics.viewCount;
        $('.views').text(views);
    });
    

    This code gets the view count from the JSON response and updates the .views element with that count.

    With these changes, your code should now display the view count for the specified YouTube video. Note that you will need to have a valid YouTube Data API key and include it in your API request to retrieve the view count.

    Login or Signup to reply.
  2. Here is a more abstract approach for reusability and using plain javascript functions.

    We declare a function for the API call which returns a promise. Then we declare a function that returns only the viewCount property from the API response.

       function getVideoResponse(video_id) {
            const API_KEY = 'XXX-XXX-XXX-XXX'
            const endpoint = `https://www.googleapis.com/youtube/v3/videos?id=${video_id}&key=${API_KEY}&part=snippet,statistics`
            return new Promise((resolve, reject) => {
                fetch(endpoint)
                    .then((response) => response.json())
                    .then((data) => {
                        /**
                         * We return the first item of the array
                         * If we insert the parameter statistics at the youtube API endpoint
                         * then an object with the below structure is returned from the API call
                         * 
                         * commentCount: string
                         * favoriteCount: string
                         * likeCount: string
                         * viewCount: string
                         */
                        resolve(data.items[0]);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        }
        
        async function getYouTubeViewCount(video_id) {
            // We destructure the statistics object and then access viewCount property as described ton api call method above 
            const {statistics} = await getVideoResponse(video_id);
            return statistics.viewCount;
        }
        
        // Call the function to get the views count
        getYouTubeViewCount('VIDEO_ID-XXX-XXX').then((viewsCount) => {
            // do something with the views count here
        })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search