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
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:
jsonUrl
variable with the following:Replace YOUR_API_KEY with your own YouTube Data API key.
$.getJSON
function to handle the API response and update the view count on the page. Replace the existing$.getJSON
function with the following: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.
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.