How to Parse an Rss Feed Using JavaScript

How to parse an RSS feed using JavaScript?

Parsing the Feed

With jQuery's jFeed

(Don't really recommend that one, see the other options.)

jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});

With jQuery's Built-in XML Support

$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);

console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});

With jQuery and the Google AJAX Feed API

$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});

But that means you're relient on them being online and reachable.


Building Content

Once you've successfully extracted the information you need from the feed, you could create DocumentFragments (with document.createDocumentFragment() containing the elements (created with document.createElement()) you'll want to inject to display your data.


Injecting the content

Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.

Something like:

$('#rss-viewer').append(aDocumentFragmentEntry);

or:

$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;

Test Data

Using this question's feed, which as of this writing gives:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
<title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
<link rel="self" href="https://stackoverflow.com/feeds/question/10943544" type="application/atom+xml" />
<link rel="hub" href="http://pubsubhubbub.appspot.com/" />
<link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
<subtitle>most recent 30 from stackoverflow.com</subtitle>
<updated>2012-06-08T06:36:47Z</updated>
<id>https://stackoverflow.com/feeds/question/10943544</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license>
<entry>
<id>https://stackoverflow.com/q/10943544</id>
<re:rank scheme="http://stackoverflow.com">2</re:rank>
<title type="text">How to parse a RSS feed using javascript?</title>
<category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="javascript"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="html5"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="jquery-mobile"/>
<author>
<name>Thiru</name>
<uri>https://stackoverflow.com/users/1126255</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
<published>2012-06-08T05:34:16Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html">
<p>I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don't know whether it is possible or not. If any one knows please help me on this. Thanks in advance.</p>

</summary>
</entry>
<entry>
<id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
<re:rank scheme="http://stackoverflow.com">1</re:rank>
<title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
<author>
<name>haylem</name>
<uri>https://stackoverflow.com/users/453590</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
<published>2012-06-08T05:43:24Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html"><h1>Parsing the Feed</h1>

<h3>With jQuery's jFeed</h3>

<p>Try this, with the <a href="http://plugins.jquery.com/project/jFeed" rel="nofollow">jFeed</a> <a href="http://www.jquery.com/" rel="nofollow">jQuery</a> plug-in</p>

<pre><code>jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
</code></pre>

<h3>With jQuery's Built-in XML Support</h3>

<pre><code>$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);

console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
</code></pre>

<h3>With jQuery and the Google AJAX APIs</h3>

<p>Otherwise, <a href="https://developers.google.com/feed/" rel="nofollow">Google's AJAX Feed API</a> allows you to get the feed as a JSON object:</p>

<pre><code>$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed &amp;&amp; data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
</code></pre>

<p>But that means you're relient on them being online and reachable.</p>

<hr>

<h1>Building Content</h1>

<p>Once you've successfully extracted the information you need from the feed, you need to create document fragments containing the elements you'll want to inject to display your data.</p>

<hr>

<h1>Injecting the content</h1>

<p>Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.</p>
</summary>
</entry></feed>

Executions

Using jQuery's Built-in XML Support

Invoking:

$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);

console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});

Prints out:

------------------------
title : How to parse a RSS feed using javascript?
author :
Thiru
https://stackoverflow.com/users/1126255

description:
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author :
haylem
https://stackoverflow.com/users/453590

description:

Using jQuery and the Google AJAX APIs

Invoking:

$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('https://stackoverflow.com/feeds/question/10943544'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});

Prints out:

------------------------
title : How to parse a RSS feed using javascript?
author : Thiru
description: undefined
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author : haylem
description: undefined

How To Parse Blogger Rss feed Using Javascript and get output on a HTML Page?

Why not using blogger JSON feed, It is lightweight compared to XML feed (used in Atom and RSS) You can use ?alt=json parameter to access json feed like this

https://www.universalmanual.com/feeds/posts/default?alt=json

To parse JSON feed using javascript use ?alt=json-in-script
The following example shows the last post title from your blog

<div id="content"></div>

<script>
function get(json) {

document.getElementById('content').innerHTML = "<h2>" + json.feed.entry[0].title.$t + "</h2>";
}
</script>

<script src="https://www.universalmanual.com/feeds/posts/default?alt=json-in-script&callback=get"></script>

To show post image in your code:

<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://www.universalmanual.com/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>

Parse RSS content:encoded with native javaScript

So, it seems that I needed to use the tag getElementsByTagNameNS and that the node was "encoded" - like this:

var content = item.getElementsByTagNameNS("*", "encoded").item(0).textContent;

parse rss feed using javascript

Try changing the last line of the httpGet function to:

return xmlHttp.responseXML;

After all, you are expecting an XML response back. You may also need to add this line to your PHP proxy:

header("Content-type: text/xml");

To force the return content to be sent as XML.

Parse RSS title into HTML using Javascript

Based on the answer you found as well, I put together a jsfiddle for testing purposes. (note that I'm using a predefined XML string in the fiddle since I can't access the RSS feed on the domain)

Here's the code explanation

Simple HTML:

<ul id="feed">
</ul>

Javascript:

$(document).ready(function(){

var x=10; // your X iteration limit

// load the xml data. it is parsed by jquery
$.get("http://www.flatpanels.dk/rss/nyhed.xml", function(data) {
var $xml = $(data);

$xml.find("item").each(function(i, val) { // find the items in the rss and loop

// create an item object with all the necessary information out of the xml
var $this = $(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text(),
description: $this.find("description").text(),
pubDate: $this.find("pubDate").text(),
author: $this.find("author").text(),
guid: $this.find("guid").text()
};
// replace the CDATA in the item title
item.title = item.title.replace("<![CDATA[", "").replace("]]>", "");

// #feed selects the ul element with the id feed
// and append() appends a newly created li element
// to the ul
$('#feed').append($('<li><a href="' +item.guid +'">' +item.title +'</a></li>'));

return i<(x-1); // (stop after x iterations)
});
});
});

How to parse rss feed in xml format instead of json format from url - Ionic 2

This code will generate two objects: info which holds informations such as title, description ..., and items which is an array of object representing the items.

The names of the properities of these objects are either tag names or attribute names, and they're following the same heirarchy as the XML data. Now since they are objects, it will be easy to access their data for example:

// Info object
var title = info.title;
var imgUrl = info.image.url;
//...

// Items array
items.forEach(function(item){
var itemTitle = item.title;
var itemEnclosureUrl = item.enclosure.url;
//...
});

var data = '<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0"><channel><title>Site Name</title><link>http://www.my-site.it/home</link><description>Site description</description><pubDate>Sat, 14 Jan 2017 11:36:51 +0100</pubDate><image><url>http://www.image.it/uploads/../images/rss.jpg</url><title><![CDATA[Site Name]]></title><link>http://www.sitename.it/home</link></image><generator>Zend_Feed</generator><language>en</language><docs>http://blogs.law.harvard.edu/tech/rss</docs><item><title><![CDATA[Title]]></title><link>http://link</link><description>Description</description><pubDate>Sat, 14 Jan 2017 10:28:00 +0100</pubDate><enclosure url="http://image-url.jpg" type="image/jpeg" length="110"/></item></channel></rss>';

var parser = new DOMParser();var xmlData = parser.parseFromString(data, "application/xml");
// First get the information (title, description, ...)var info = {};(xmlData.querySelectorAll("channel>*:not(item)") || []).forEach(function(e){ var infoData = {}; var found = false; e.childNodes.forEach(function(e){ // skip text nodes if(e.nodeType == 3) return; found = true; infoData[e.tagName] = e.textContent; }); if(found) info[e.tagName] = infoData; else info[e.tagName] = e.textContent;});
// Then, get the list of itemsvar items = [];(xmlData.querySelectorAll("channel>item") || []).forEach(function(item){ var itemData = {}; item.childNodes.forEach(function(e){ // skip over text nodes if(e.nodeType == 3) return;
// get attributes if exist (to support the 'enclosure' element) var attr = {}; var found = false; for(var i = 0, atr = e.attributes, l = e.attributes.length; i < l; i++){ found = true; attr[atr[i].name] = atr[i].value; } if(found) itemData[e.tagName] = attr; else itemData[e.tagName] = e.textContent; }); items.push(itemData);});
console.log("INFO: ", info);console.log("ITEMS: ", items);


Related Topics



Leave a reply



Submit