RSS Web Widget

Exclusive offer: get 50% off this eBook here
Object-Oriented JavaScript

Object-Oriented JavaScript — Save 50%

Create scalable, reusable high-quality JavaScript applications and libraries

$23.99    $12.00
by Roshan Bhattarai | April 2009 | AJAX MySQL PHP Web Development

If you're visiting a web page like a blog or news portal which frequently updates its content then you're most likely to see a link for subscribing RSS feed or articles or news. The main purpose of an RSS feed is to provide the latest updates of articles, posts, news headlines, or audio and video, in a standard format—without the need to visit that website. These RSS feeds are stored in specified URLs and can be read using software which are commonly called RSS Readers, Feed Readers or Feed Aggregators. These can be web based applications or desktop based.

In this article by Roshan Bhattarai, we'll see how to create a web widget which displays the links from the RSS feed of a specific URL. By the end of this article, you'll see how we can use Iframe to build a web widget.

What is an RSS Feed?

First of all, let us understand what a web feed is. Basically, it is a data format that provides frequently updated content to users. Content distributors syndicate the web feed, allowing users to subscribe, by using feed aggregator. RSS feeds contain data in an XML format.

RSS is the term used for describing Really Simple Syndication, RDF Site Summary, or Rich Site Summary, depending upon the different versions.

RDF (Resource Description Framework), a family of W3C specification, is a data model format for modelling various information such as title, author, modified date, content etc through variety of syntax format. RDF is basically designed to be read by computers for exchanging information.

Since, RSS is an XML format for data representation, different authorities defined different formats of RSS across different versions like 0.90, 0.91, 0.92, 0.93, 0.94, 1.0 and 2.0. The following table shows when and by whom were the different RSS versions proposed.

RSS Version

Year

Developer's Name

RSS 0.90

1999

Netscape introduced RSS 0.90.

RSS 0.91

1999

Netscape proposed the simpler format of RSS 0.91.

1999

UserLand Software proposed the RSS specification.

RSS 1.0

2000

O'Reilly released RSS 1.0.

RSS 2.0

2000

UserLand Software proposed the further RSS specification in this version and it is the most popular RSS format being used these days.

Meanwhile, Harvard Law school is responsible for the further development of the RSS specification.

There had been a competition like scenario for developing the different versions of RSS between UserLand, Netscape and O'Reilly before the official RSS 2.0 specification was released. For a detailed history of these different versions of RSS you can check http://www.rss-specifications.com/history-rss.htm

The current version RSS is 2.0 and it is the common format for publishing RSS feeds these days.

Like RSS, there is another format that uses the XML language for publishing web feeds. It is known as ATOM feed, and is most commonly used in Wiki and blogging software. Please refer to http://en.wikipedia.org/wiki/ATOM for detail.

The following is the RSS icon that denotes links with RSS feeds.

RSS Web Widget

If you're using Mozilla's Firefox web browser then you're likely to see the above image in the address bar of the browser for subscribing to an RSS feed link available in any given page.

Web browsers like Firefox and Safari discover available RSS feeds in web pages by looking at the Internet media type application/rss+xml. The following tag specifies that this web page is linked with the RSS feed URL:

http://www.example.com/rss.xml
<link href="http://www.example.com/rss.xml" rel="alternate"
type="application/rss+xml" title="Sitewide RSS Feed" />

Example of RSS 2.0 format

First of all, let’s look at a simple example of the RSS format.

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>Title of the feed</title>
<link>http://www.examples.com</link>
<description>Description of feed</description>
<item>
<title>News1 heading</title>
<link>http://www.example.com/news-1</link>
<description>detail of news1 </description>
</item>
<item>
<title>News2 heading</title>
<link>http://www.example.com/news-2</link>
<description>detail of news2 </description>
</item>
</channel>
</rss>

The first line is the XML declaration that indicates its version is 1.0. The character encoding is UTF-8. UTF-8 characters support many European and Asian characters so it is widely used as character encoding in web. The next line is the rss declaration, which declares that it is a RSS document of version 2.0

The next line contains the <channel> element which is used for describing the detail of the RSS feed. The <channel> element must have three required elements <title>, <link> and <description>. The title tag contains the title of that particular feed. Similarly, the link element contains the hyperlink of the channel and the description tag describes or carries the main information of the channel. This tag usually contains the information in detail.

Furthermore, each <channel> element may have one or more <item> elements which contain the story of the feed. Each <item> element must have the three elements <title>, <link> and <description> whose use is similar to those of channel elements, but they describe the details of each individual items.

Finally, the last two lines are the closing tags for the <channel> and <rss> elements.

Creating RSS Web Widget

The RSS widget we're going to build is a simple one which displays the headlines from the RSS feed, along with the title of the RSS feed. This is another widget which uses some JavaScript, PHP CSS and HTML. The content of the widget is displayed within an Iframe so when you set up the widget, you've to adjust the height and width.

RSS Web Widget

To parse the RSS feed in XML format, I've used the popular PHP RSS Parser – Magpie RSS. The homepage of Magpie RSS is located at http://magpierss.sourceforge.net/.

Introduction to Magpie RSS

Before writing the code, let's understand what the benefits of using the Magpie framework are, and how it works.

  1. It is easy to use.
  2. While other RSS parsers are normally limited for parsing certain RSS versions, this parser parses most RSS formats i.e. RSS 0.90 to 2.0, as well as ATOM feed.
  3. Magpie RSS supports Integrated Object Cache which means that the second request to parse the same RSS feed is fast— it will be fetched from the cache.

Now, let's quickly understand how Magpie RSS is used to parse the RSS feed. I'm going to pick the example from their homepage for demonstration.

require_once 'rss_fetch.inc';

$url = 'http://www.getacoder.com/rss.xml';
$rss = fetch_rss($url);

echo "Site: ", $rss->channel['title'], "<br>
";
foreach ($rss->items as $item ) {
$title = $item[title];
$url = $item[link];
echo "<a href=$url>$title</a></li><br>
";
}

If you're more interested in trying other PHP RSS parsers then you might like to check out SimplePie RSS Parser (http://simplepie.org/) and LastRSS (http://lastrss.oslab.net/).

You can see in the first line how the rss_fetch.inc file is included in the working file. After that, the URL of the RSS feed from getacoder.com is assigned to the $url variable. The fetch_rss() function of Magpie is used for fetching data and converting this data into RSS Objects. In the next line, the title of RSS feed is displayed using the code $rss->channel['title'].

The other lines are used for displaying each of the RSS feed's items. Each feed item is stored within an $rss->items array, and the foreach() loop is used to loop through each element of the array.

Writing Code for our RSS Widget

As I've already discussed, this widget is going to use Iframe for displaying the content of the widget, so let's look at the JavaScript code for embedding Iframe within the HTML code.

var widget_string = '<iframe 
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://www.yourserver.com/rsswidget/rss_parse_handler.php?rss_url=';
widget_string += encodeURIComponent(rss_widget_url);
widget_string += '&maxlinks='+rss_widget_max_links;
widget_string += '" height="'+rss_widget_height+'" width="'+rss_widget_width+'"';
widget_string += ' style="border:1px solid #FF0000;"';
widget_string +=' scrolling="no" frameborder="0"></iframe>';
document.write(widget_string);

In the above code, the widget string variable contains the string for displaying the widget. The source of Iframe is assigned to rss_parse_handler.php. The URL of the RSS feed, and the headlines from the feed are passed to rss_parse_handler.php via the GET method, using rss_url and maxlinks parameters respectively. The values to these parameters are assigned from the Javascript variables rss_widget_url and rss_widget_max_links.

The width and height of the Iframe are also assigned from JavaScript variables, namely rss_widget_width and rss_widget_height. The red border on the widget is displayed by assigning 1px solid #FF0000 to the border attribute using the inline styling of CSS. Since, Inline CSS is used, the frameborder property is set to 0 (i.e. the border of the frame is zero).

Displaying borders from the CSS has some benefit over employing the frameborder property. While using CSS code, 1px dashed #FF0000 (border-width border-style border-color) means you can display a dashed border (you can't using frameborder), and you can use the border-right, border-left, border-top, border-bottom attributes of CSS to display borders at specified positions of the object.

The scrolling property is set to no here, which means that the scroll bar will not be displayed in the widget if the widget content overflows. If you want to show a scroll bar, then you can set this property to yes.

The values of JavaScript variables like rss_widget_url, rss_widget_max_links etc come from the page where we'll be using this widget. You'll see how the values of these variables will be assigned from the section at the end where we'll look at how to use this RSS widget.

 

Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

PHP Code

We have looked at the JavaScript code, now let's look at the code of rss_parse_handler.php.

First of all, a style sheet called rss_widget.css, is attached to this page.

<link rel="stylesheet" type="text/css" href="rss_widget.css" />

Now, we define a user defined error handler function, to handle any error warning that may occur while executing the PHP script.

function custom_error_handler($errno, $errstr) 
{
echo '<span class="phperror">'.htmlentities($errstr).'</span>';
}
set_error_handler('custom_error_handler');

The set_error_handler() function allows you to define custom means of handling errors at runtime which allow you to display a warning message, in a stylish way, at runtime.

You might know that the error_reporting() function of PHP can be used to set different levels for displaying errors. We can completely turn it off by using the error_reporting(0); statement.

But the error_reporting() settings will have no effect on your custom error handler function made from set_error_handler() and it will be called regardless of error_reporting().

You might have noticed that the error handler function custom_error_handler() contains two parameters, so let's look at them here:

  1. errno: This parameter contains the level of error raised and contains as an integer.
  2. errstr: This parameter contains the error message as a string.

Let's look at the remaining code of rss_parse_handler.php

$widget_string='';
$max_feed_links = intval($_GET['maxlinks']);
$feed_url = urldecode($_GET['rss_url']);

The $widget_string contains the html string for displaying the title and headlines. It is initialized as an empty string at the beginning. The $max_feed_links variable contains the value passed, via the parameter maxlinks, and the value is converted into an integer, (which was actually the string when passed via the URL, using the intval() function of PHP).

The $feed_url variable contains the value of the parameter rss_url and is passed via the GET method in a URL decoded format using the urldecode() function of PHP. This is encoded using the encodeURIComponent() function of JavaScript.

Now, look at the remaining PHP code for parsing and displaying the items of RSS feed.

require_once 'rss_fetch.inc';
$feed_data = @fetch_rss($feed_url);
$feed_title = $feed_data->channel['title'];
$widget_string.='<div id="rss_widget_box">';
$widget_string.='<div class="rss_title">'.$feed_title.'</div>';
$count=0;
foreach ($feed_data->items as $feed_item)
{
$widget_string.='<div class="rss_links">
<a href="'.$feed_item['link'].'">'.$feed_item['title'].'</a></div>';
$count++;
if($count>=$max_feed_links)
break;
}

$widget_string.='</div>';
echo $widget_string;

Most of the coding of this part is already discussed above while describing Magpie RSS in detail.

The @ symbol in front of fetch_rss() function is known as the error control operator in PHP. When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

It should be noticed in the above code that the whole content of the widget is contained within the division rss_widget_box. In turn, the title of the feed is inside the division with the class rss_title, and the links to the RSS headlines are within the division with the class rss_links.

Finally, the content of the $widget_string is printed in the browser using an echo statement.

Style definition in CSS file

Let's now look at the style defined in CSS file.

body
{
background-color:#333333;
font-family:Arial, Helvetica, sans-serif;
}
.phperror
{
color:#FF0000;
font-size:10px;
}
#rss_widget_box
{
padding:2px;
}
.rss_title
{
color:#FFCCCC;
font-size:14px;
font-weight:bold;
padding:3px;
}
.rss_links
{
margin: 3px 1px;
}
.rss_links a
{
color:#CCFFFF;
font-size:11px;
font-weight:bold;
}

The first style is defined for the body tag. The property assigned to this tag will be assigned to the whole document. Subsequently, the class is defined with the name phperror, you might have noticed that this class is used within the span (inside the custom error handler function custom_error_handler() of PHP). # is the id selector for CSS and used here for styling the division with id rss_widget_box.

The difference between ".rss_links" and ".rss_links a" is that the styling of the rss_links class will be applied to the element which uses the class rss_links. While ".rss_links a" styling will be applied to all the anchor element(s)(<a></a> tag) inside the elements using the class rss_links.

Putting the code all together

Since we've dissected the code in sections, let's compile them into single files.

Create a rss_widgert.js file and add the following code to it.

var widget_string = '<iframe 
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://localhost/bookcode/rsswidget/rss_parse_handler.php?rss_url=';
widget_string += encodeURIComponent(rss_widget_url);
widget_string += '&maxlinks='+rss_widget_max_links;
widget_string += '" height="'+rss_widget_height+'" width="'+rss_widget_width+'"';
widget_string += ' style="border:1px solid #FF0000;"';
widget_string +=' scrolling="no" frameborder="0"></iframe>';
document.write(widget_string);

Now, create a rss_parse_handler.php file and add the following code.

<html>
<head>
<link rel="stylesheet" type="text/css" href="rss_widget.css" />
</head>
<body>
<?php

function custom_error_handler($errno, $errstr)
{
echo '<span class="phperror">'.htmlentities($errstr).'</span>';
}
set_error_handler('custom_error_handler');
$widget_string='';
$max_feed_links = intval($_GET['maxlinks']);
$feed_url = urldecode($_GET['rss_url']);
require_once 'rss_fetch.inc';
$feed_data = @fetch_rss($feed_url);
$feed_title = $feed_data->channel['title'];
$widget_string.='<div id="rss_widget_box">';
$widget_string.='<div class="rss_title">'.$feed_title.'</div>';
$count=0;
foreach ($feed_data->items as $feed_item)
{
$widget_string.='<div class="rss_links">
<a href="'.$feed_item['link'].'">'.$feed_item['title'].'</a></div>';
$count++;
if($count>=$max_feed_links)
break;
}

$widget_string.='</div>';
echo $widget_string;

?>
</body>
</html>

After that, create a rss_widget.css file and add the following code to it.

body
{
background-color:#333333;
font-family:Arial, Helvetica, sans-serif;
}
.phperror
{
color:#FF0000;
font-size:10px;
}
#rss_widget_box
{
padding:2px;
}
.rss_title
{
color:#FFCCCC;
font-size:14px;
font-weight:bold;
padding:3px;
}
.rss_links
{
margin: 3px 1px;
}
.rss_links a
{
color:#CCFFFF;
font-size:11px;
font-weight:bold;
}

Using RSS widget

To use this RSS widget we need to follow these steps:

  1. Download Magpie RSS library from http://magpierss.sourceforge.net/ then extract it and upload it to the http://yourhost.com/rsswidget/ directory of your server.
  2. Next, we need to upload rss_widget.css, rss_widget.js and rss_widget_parse.php to a PHP enabled web server in the same URL-http://yourhost.com/rsswidget/, so that it can be used by the client websites.
  3. Now, we can place the widget in any webpage by inserting the following JavaScript Code into the webpage:
<script type="text/javascript" language="javascript">
var rss_widget_url='http://www.getacoder.com/rss.xml';
var rss_widget_max_links=5;
var rss_widget_width=250;
var rss_widget_height=120;
</script>
<script type="text/javascript" language="javascript"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/rsswidget/rss_widget.js"></script>

Remember that the values of the variables rss_widget_url, rss_widget_max_links, rss_widget_width and rss_widget_height are customizable and you can change them according to your need.

Summary

RSS feeds are XML data formats for providing real time website updates. These RSS feeds can be read in a single place by using an RSS reader or Aggregator. In this article, we've learnt how to create the widget which parses the RSS feed of a provided URL, and subsequently displays the title and headline with hyperlinks.

 

If you have read this article you may be interested to view :

Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Roshan Bhattarai is an experienced web developer. His core proficiency lies in JAVASCRIPT, CSS, XHTML, PHP and MySQL. Having done his masters in information technology, he has many active websites to his credit. He has worked in various companies as a Technical Lead before moving on as a freelancer. He primarily resolves problems faced by programmers, liaise with the clients to have a better understanding of the projects' requirement and does research on new technologies relating to the project. He also excels in analysis and design of the database and work flow of a web project. He also excels in analysis and design of the database and work flow of a web project. He can be contacted on his blog http://roshanbh.com.np.

Books From Packt

DWR Java AJAX Applications
DWR Java AJAX Applications

Learning Ext JS
Learning Ext JS

Google Web Toolkit GWT Java AJAX Programming
Google Web Toolkit GWT Java AJAX Programming

WordPress Plugin Development (Beginner's Guide)
WordPress Plugin Development (Beginner's Guide)

Learning Dojo
Learning Dojo

Drupal 6 JavaScript and jQuery: RAW
Drupal 6 JavaScript and jQuery: RAW

Learning jQuery 1.3
Learning jQuery 1.3

PHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax
PHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax

 

 

 

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software