Loading RSS feed with AJAX: alternatives to Google Feed API? - javascript

I've been using the Google Feed API to load RSS feeds, but it looks like Google has shut down the API. For instance, when I try to load the New York Times RSS feed at http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&q=http%3A%2F%2Frss.nytimes.com%2Fservices%2Fxml%2Frss%2Fnyt%2FHomePage.xml, I get this response:
{"responseData": null, "responseDetails": "This API is no longer available.", "responseStatus": 403}
Are there any viable alternatives?

Use Yahoo's YQL API:
select * from xml where url = 'https://news.ycombinator.com/rss'
You can request a JSONP feed by adding a callback parameter to the url
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20'https%3A%2F%2Fnews.ycombinator.com%2Frss'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=mycallback

Deprecated
My plugin, $.jQRSS uses Google Feed and seems to work just fine, given your exact RSS link:
var rss = 'http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml';
$.jQRSS(rss, { count: 8 }, function (feed, entries) {
console.log([feed, entries]);
$.each(entries, function(i) {
if (this['content']) {
var fieldset = $('<fieldset/>', { title: this.contentSnippet }).appendTo('body'),
legend = $('<legend/>').appendTo(fieldset),
$link = $('<a />', { href: this.link, html: this.title, target: '_blank' }).appendTo(legend),
$date = $('<h5 />', { html: this.publishedDate }).appendTo(fieldset),
$content = $('<div />', { html: this.content }).appendTo(fieldset);
$content.find('br').remove();
}
});
});
fieldset > h5 { float: right; margin-top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://rawgit.com/JDMcKinstry/jQRSS/master/jQRSS.js"></script>

You can use the script feedburner:
<script src="http://feeds.feedburner.com/feeduri?format=sigpro&nItems=10" type="text/javascript"></script>
All information:
https://support.google.com/feedburner/answer/78991?hl=en

One addition to Tony's solution for using YQL - I needed to change the callback value to JSON_CALLBACK to parse the response properly:
'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20\'' + encodeURIComponent(url) + '\'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=JSON_CALLBACK'

You can use PHP to grab a copy of whatever RSS feed you wish to display, then use client side JavaScript to display the results. The main advantage is you're not subject to daily requests limits that way, which most free RSS API services have, or reliability issues.
http://www.javascriptkit.com/dhtmltutors/ajaxticker/index.shtml

Related

twitter sharing button bit.ly integration on a static website

I am trying to integrate bit.ly on my website in JS to short my url. All my url are too long, what will be the most straight foward way to use the bit.ly restful api for sharing button on a static website in HTML/javascript.
The result I want to get is when my user click share on my website the url is automatically shortened by bit.ly
here is the code I am currently using to share my pages dynamically on twitter:
<script type="text/javascript" charset="utf-8" src="http://bit.ly/javascript-api.js?version=latest&login=LOGINID&apiKey=APIKEY"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
function tweetCurrentPage()
{ window.open("https://twitter.com/share?url=" + escape(window.location.href) + "&text=" + document.title, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600'); return false; }
var TweetThisLink = {
shorten : function(e) {
e.preventDefault();
var url = this.href.substr(this.href.indexOf('http:',5))
BitlyClient.shorten(url, 'TweetThisLink.response');
},
response : function(data) {
var bitly_link = null;
for (var r in data.results) {
bitly_link = data.results[r]['shortUrl'];
break;
}
var tweet_text = "I am reading documentation of"
document.location = "http://twitter.com/share?url=" + encodeURIComponent(tweet_text + ' ' + bitly_link);
}
}
jQuery('.tweetlink').bind('click', TweetThisLink.shorten);
</script>
tweet this link
Not sure if this is on purposefully obfuscated for the sake of the question, but
In your script tag the src is:
"http://bit.ly/javascript-api.js?version=latest&login=LOGINID&apiKey=APIKEY".
LOGINID & apiKey are placeholders are in-place. You need to replace them with the appropriate keys you should receive from bitly.
if this is on purpose for the sake of the question please ignore this answer.
don't know why but my function "tweetCurrentPage()" for dynamic url won't work it's giving me a respond INVALID_URI from bit.ly, but if I hard code the href value like this twitter.com/share?url=+exemple.com"; it's working...

Saving JSON output of a form action call in a JavaScript variable?

I have an HTML form with an action that queries an external service.
When I submit the form, I land on the page of the external website. This website only lists JSON output.
Is there any way I can store this object in a JavaScript variable?
<form action="http://rdio-service.herokuapp.com//search?q=" method="get" target="_top" >
Input artist: <input type="text" name="q"><br>
<button>Find songs</button>
</form>
http://jsfiddle.net/85sofgaj/
I've heard about the JQuery method $.getJSON but it looks like that only works with local data.
Cross-Domain Ajax without jQuery
OP asks how to query a web service that returns music data in json format. However, the web service is "external" and requires a cross-domain ajax request. Browsers block these requests ("access denied") unless authorized by the server. Typically, the server must set the request header "Access-Control-Allow-Origin" specifying who is allowed to make queries and provide a jsonp response. And in this case it appears the web service is not configure for it. For more info see: MDN HTTP access control (CORS)
One way to overcome this problem is to use a proxy server. The proxy makes the request on behalf of the client. The example below sends a request to Yahoo YQL which requests the data for us and then sends it back in jsonp format. (Yahoo, Google, and others offer this service)
Run the Example to Test:
I've tried to keep this fairly simple to illustrate the technique. It searches and displays a list of music album titles and covers. Also, it can take a few seconds for the service to respond.
<html>
<body>
<style type="text/css">
#output table { border-collapse: collapse; font-family: sans-serif; font-size: 16px;}
#output td { border: 1px lightgray solid; padding: 2px;}
#output img {height: 100px; width: auto; }
</style>
Enter keywords:
<input id="keyword" type="text" value="Bach"><button onclick="search()">Search...</button>
<div id="output"></div>
<script type="text/javascript">
// jsonp callback
function callback( obj ) {
var i, data, html='';
try {
data = obj.query.results.json.data;
for(i=0; i<data.length; i++) {
html += '<tr><td><img src="' + data[i].icon + '"></td><td>' + data[i].name + '</td></tr>';
}
html = '<table>' + html + '</table>';
}
catch(e) { html = 'No search results.' }
document.getElementById('output').innerHTML = html;
}
// cross-domain ajax via proxy
function search( ) {
var proxy, query, options, keyword, head, script;
keyword = document.getElementById('keyword').value;
keyword = keyword.replace(/\s/g,'+');
proxy = 'https://query.yahooapis.com/v1/public/yql';
query = "?q=" + encodeURIComponent( "select * from json where url='http://rdio-service.herokuapp.com//search?q=" + keyword + "'" );
options = '&diagnostics=true&format=json&callback=callback';
head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
script = document.createElement('script');
script.type = 'text/javascript';
script.src = proxy + query + options;
head.appendChild( script );
}
search( );
</script>
</body>
</html>
The service returns an array of objects such as:
"data": [
{
"object_type": "search_result",
"id": "t4727843",
"name": "Didgeridoo",
"url": "/artist/Duke_Ellington/album/The_Afro-Eurasian_Eclipse_(Remastered)/track/Didgeridoo/",
"length": "32",
"radio_id": "sr4727843",
"type": "track",
"icon": "http://rdio1img-a.akamaihd.net/album/f/b/d/000000000005ddbf/3/square-200.jpg"
},
more records ...
You can. Why don't you just download result with jQuery get method?
Like this:
$(document).ready(function(){
$('#btnDownloadJSON').click(function(){
$.get('http://rdio-service.herokuapp.com//search?q=jay',function(r){
alert(r.data);
});
});
});
"r" variable is JavaScript object already. It's parsed from JSON string.

Update multiple div from json file every sec without page flicker

I wrote the script below to get values from a Json file that is stored inside a industrial automation equipment. The script is inside a HTML page that is stored in a PC and replaces Div contents based on its ID. Note: I can't run any code on the industrial equipment. This is not a "real server". It just stores Json files and update its values based in real sensors.
Script inside index.html
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
</script>
<script type="text/javascript" src="http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
ensaio.json file
callback({
'Inicia': ':="ENSAIO".CMDS.LIBERA:',
'Rearme': ':="ENSAIO".CMDS.RESET:',
'Nro_Serie': ':="ENSAIO".Nro_Serie:',
'Modelo': ':="ENSAIO".Modelo:',
'Nro_Ensaio': ':="ENSAIO".Nro_Ensaio:',
'Pronto': ':="ENSAIO".Pronto:',
'Data': ':="ENSAIO".Data:',
'Hora': ':="ENSAIO".Hora:',
'SP_Pelotas': ':="ENSAIO".SP_Pelotas:',
'PV_Pelotas': ':="ENSAIO".PV_Pelotas:',
'Status': ':="ENSAIO".Status:'
});
When I open index.html in a browser I can view all values on the places that I really want, but I need a way to get this values refreshed. I tried to refresh the page using the script below, but div values flickers every time.
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(5000);">
How can I update div contents from the Json file every second without flickering the page?
Very important Information: I can't enable cross-domain requests on this "server".
More information about creating pages for this equipment here! http://www.dmcinfo.com/latest-thinking/blog/articletype/articleview/articleid/8567/siemens-s7-1200-web-server-tutorial--from-getting-started-to-html5-user-defined-pages
Thanks!
I tryed to do this script below.
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
setInterval(callback,1000);
</script>
<script type="text/javascript" src="192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
Ensaio.json Content
callback({
'Inicia': '0',
'Rearme': '0',
'Nro_Serie': '010',
'Modelo': 'CPT001',
'Nro_Ensaio': '138',
'Pronto': '0',
'Data': '18-07-2014',
'Hora': '10-02',
'SP_Pelotas': '40',
'PV_Pelotas': '1',
'Status': 'ENSAIO',
'Nome': 'Test',
'Descricao': 'Test1'
});
I tried changing the src attribute of the script tag in Javascript, but it seems as though the script tag needs to be replaced for the script to load. Here's a function that takes a script URI and an interval and then reloads the script indefinitely, without piling up a bunch of script tags:
var scriptLoader = (function () {
var head = document.getElementsByTagName("head")[0];
return function (scriptURI, interval) {
var scriptElement = null;
setInterval(function () {
var newScriptElement = document.createElement('script');
newScriptElement.type = 'text/javascript';
newScriptElement.onerror = function (error) {
throw new URIError('Could not load script ' + error.target.src);
};
if (scriptElement) {
head.replaceChild(newScriptElement, scriptElement);
} else {
head.appendChild(newScriptElement);
}
newScriptElement.src = scriptURI;
scriptElement = newScriptElement;
}, interval);
}
}());
It's used like this:
window.onload = function () {
scriptLoader("http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json", 10000);
};
[EDIT: this answer is only valid if you can set Access-Control-Allow-Origin headers on your server. also, my answer is sans jquery.]
if i understand you correctly, the name for what you are trying to do is asyncronous http requests. that means that you want to get more information from a server without reloading the whole page. the javascript technology that is used to do so is called ajax or XHR. here is an example of how to use ajax. you will want to replace the URL in xmlhttp.open("GET","ajax_info.txt",true); with the (complete) URL of the file on the server you want to access, i.e. http://..... the response that your requests gets from the server is stored in xmlhttp.responseText where xmlhttp is the name of the variable assigned to the ajax request.
[EDIT: in light of new information, maybe you'd prefer reloading an iframe than the whole page? not an awesome solution but iframes don't require cross-site request.]

Using GM xmlhttpRequest instead of an iframe to display pertinent info from an external page

I have loaded an https page on Amazon.co.uk and I wish to display use 'GM xmlhttpRequest' to request the price of an item on a linked page.
What I’ve been doing so far
I tried to use an iFrame to display the window:
var prodLinks = $("td.product_description a:contains('View Amazon Product Page')");
if (prodLinks.length) {
var iframeSrc = prodLinks[0].href;
iframeSrc = iframeSrc.replace (/http:\/\//, "https://")
$("body").append ('<iframe id="gmIframe" src="' + iframeSrc + '"></iframe>');
$("#gmIframe").css ( {
"position": "absolute",
"bottom": "1em",
"left": "2em",
"height": "25%",
"width": "84%",
"z-index": "17",
"background": "#00FF00"
} );
}
The problem with this approach is, that whilst it works, the contents of the iFrame is too cluttered, so I cannot see what I need to, at a glance.
The stuff I want to see
Let us suppose that the linked page is https://www.amazon.co.uk/gp/product/B001AM72BM/
The relevant HTML snippet from the aforementioned page:
<tr id="actualPriceRow">
<td id="actualPriceLabel" class="priceBlockLabelPrice">Price:</td>
<td id="actualPriceContent"><span id="actualPriceValue"><b class="priceLarge">£2.85</b></span>
<span id="actualPriceExtraMessaging">
How, exactly, can I use GM xmlhttpRequest to get the page
Background : I’m using something similar to GreaseMonkey
This is for Greasekit on Fluid.app (which is very old, but I must using it). You probably don’t even need to know that as it’s very similar to Greasekit. So, for the purposes of this question, you can just pretend it is.
My attempt at answer
I would try:
GM_xmlhttpRequest({
method: "GET",
url: "https://www.amazon.co.uk/gp/product/B001AM72BM/",
onload : function(response) {
// do something with the result here
document.getElementByClass(‘priceLarge').innerHTML = response.responseText;
}
});
Use jQuery to parse the response from GM_xmlhttpRequest, and unlike for an iframe, you don't need to rewrite the URL to SSL.
So:
Rather than add an iframe, add a node that will contain your price.
Grab the product URL as before.
Fetch the URL with GM_xmlhttpRequest.
Use jQuery to find the .priceLarge node.
Write the contents of that node to the node created in step 1.
The complete code, with some UI and error handling, looks like this. I tested it on your sample page and it works.
var prodLinks = $("td.product_description a:contains('View Amazon Product Page')");
if (prodLinks.length) {
//--- Make a place to put the price.
$("td.buybox table td.v_prod_box_topleft").append (
'<p id="gmPriceResult">Fetching...</p>'
);
GM_xmlhttpRequest ( {
method: 'GET',
url: prodLinks[0].href,
onload: getItemPrice,
onabort: reportAJAX_Error,
onerror: reportAJAX_Error,
ontimeout: reportAJAX_Error
} );
}
function getItemPrice (resp) {
/*--- Strip <script> tags and unwanted images from response
BEFORE parsing with jQuery. Otherwise the scripts will run and the
images will load -- wasting time and bandwidth and increasing risk
of complications.
*/
var respText = resp.responseText.replace (/<script(?:.|\n|\r)+?<\/script>/gi, "");
respText = respText.replace (/<img[^>]+>/gi, "");
var respDoc = $(respText);
//-- Now fetch the price node:
var priceNode = respDoc.find (".priceLarge:first");
if (priceNode.length) {
$("#gmPriceResult").text (priceNode.text () );
}
else {
$("#gmPriceResult").text ("Price not found!");
}
}
function reportAJAX_Error (resp) {
alert ('Error ' + resp.status + '! "' + resp.statusText + '"');
}

How to get number of video views with YouTube API?

The question is very simple. How to get number of video views with YouTube API?
The task is simple but I would like to use that query on large number of videos very often. Is there any way to call their Youtube API and get it? (something like facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com)
I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:
<?php
$video_ID = 'your-video-ID';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>
Ref: Youtube API - Retrieving information about a single video
You can use the new YouTube Data API v3
if you retrieve the video, the statistics part contains the viewCount:
from the doc:
https://developers.google.com/youtube/v3/docs/videos#resource
statistics.viewCount / The number of times the video has been viewed.
You can retrieve this info in the client side, or in the server side using some of the client libraries:
https://developers.google.com/youtube/v3/libraries
And you can test the API call from the doc:
https://developers.google.com/youtube/v3/docs/videos/list
Sample:
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}
Authorization: Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent: Google APIs Explorer
Response:
200 OK
- Show headers -
{
"kind": "youtube#videoListResponse",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"id": "Q5mHPo2yDG8",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
"statistics": {
"viewCount": "36575966",
"likeCount": "127569",
"dislikeCount": "5715",
"favoriteCount": "0",
"commentCount": "20317"
}
}
]
}
Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.
Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.
You will need to create an API key via Google Developer Console first.
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
alert("viewCount: " + data.items[0].statistics.viewCount);
});
</script>
Here is a small code snippet to get Youtube video views from URL using Javascript
Demo of below code
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);}
Why using any api key to retrieve a portion of public html!
Simplest unix command line demonstrative example, using curl, grep and cut.
curl https://www.youtube.com/watch?v=r-y7jzGxKNo | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1
Yes, it get the full html page, this loss has no meaning against the countless advantages.
You can use this too:
<?php
$youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
echo $youtube_view_count;
?>
Using youtube-dl and jq:
views() {
id=$1
youtube-dl -j https://www.youtube.com/watch?v=$id |
jq -r '.["view_count"]'
}
views fOX1EyHkQwc
Use the Google PHP API Client: https://github.com/google/google-api-php-client
Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html
class YouTubeVideo
{
// video id
public $id;
// generate at https://console.developers.google.com/apis
private $apiKey = 'REPLACE_ME';
// google youtube service
private $youtube;
public function __construct($id)
{
$client = new Google_Client();
$client->setDeveloperKey($this->apiKey);
$this->youtube = new Google_Service_YouTube($client);
$this->id = $id;
}
/*
* #return Google_Service_YouTube_VideoStatistics
* Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )
*/
public function getStatistics()
{
try{
// Call the API's videos.list method to retrieve the video resource.
$response = $this->youtube->videos->listVideos("statistics",
array('id' => $this->id));
$googleService = current($response->items);
if($googleService instanceof Google_Service_YouTube_Video) {
return $googleService->getStatistics();
}
} catch (Google_Service_Exception $e) {
return sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
return sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
}
YouTube Data API v3 URL Sample
Source Link
https://www.googleapis.com/youtube/v3/videos?key=[YOUR_API_KEY_HERE]&fields=items(snippet(title,tags,channelTitle,publishedAt),statistics(viewCount))&part=snippet,statistics&id=[VIDEOID]
look at yt:statistics tag.
It provides viewCount, videoWatchCount, favoriteCount etc.
Here an example that I used in my TubeCount app.
I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.
var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[#yt:name='default'](#url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(#countHint)))";
var channel = "wiibart";
$.ajax({
url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
success: function(data){
var len = data.feed.entry.length;
for(var k =0; k<len; k++){
var yt = data.feed.entry[k];
v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
}
}
});
Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API
//Define a constant so that the API KEY can be used globally across the application
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');
function youtube_video_statistics($video_id) {
$json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
$jsonData = json_decode($json);
$views = $jsonData->items[0]->statistics->viewCount;
return $views;
}
//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');
I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.
PHP JSON
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);
First go through this one by uncommenting
//var_dump(json);
and get views count as:
$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};
You can use JQuery, don't forget to replace Your-Api-Key string from the code below, follow the link to find your own Api key google developers console
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
});
</script>
This probably is not what you want but you could scrap the page for the information using the following:
document.getElementsByClassName('watch-view-count')[0].innerHTML

Categories

Resources