How to Display RSS or ATOM Feeds Without Re-Loading the Web Page Using Javascript, AJAX, and SimplePie

by Michael Shipley

August 12 2008 09:35 pm | SimplePie

Update: Version 2 adds the ability to have multiple feeds on the same page.

Download version 2 (multiple feeds): update_feed2.zip:

 

One day sbeaumont9 over at SimplePie’s tech support asked:

Has anyone implemented a SimplePie feed that updates automatically with AJAX? I’d like to be able to check for new content and have it update without a manual page refresh.

I said to myself, self, I know a little about this, I should do it, so I did. Hence, Update Feed was born. Catchy name.

 

The way it works

It’s simple. Javascript starts an interval timer. When the timer fires, an AJAX HTTP request is made to a PHP script on your server. That PHP script uses SimplePie to fetch and output your RSS or ATOM feed. The AJAX call receives that output and displays it in a DIV you designated — all without the user seeing anything happen except the feed being updated right before his or her or it’s eyes.

 

Instructions

To customize it, change the variables in the update_feed.js file global variables section (at the top).

 

var minutesBetweenUpdates = 1;

Change minutesBetweenUpdates to the number of minutes between AJAX calls to the SimplePie feed updater PHP script. Recommended: 60.

 

var feedUrl = ‘http://digg.com’;

Change feedUrl to the feed you want displayed.

 

var scriptUrl = ‘http://localhost/update_feed/update_feed.php’;

Change scriptUrl to the url of the update_feed.php script.

 

var cacheDuration = 0;

Change cacheDuration to the SimplePie cache duration you desire. Recomend: 3600.

 

var divId = ‘feedDiv’;

Change divId to the id of the DIV you want the feed html to display in.

 

var countDownTimerDivId = ‘countDownTimer’;

Optionally, if you want to dispay the countdown timer, change countDownTimerDivId to the DIV id where you want the timer to display.

 

Modify update_feed.php PHP script to format the RSS or ATOM feed as you desire.

 

Finished. Upload the update_feed folder to your web server.

 

Example usage

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Demo: Update Feed using SimplePie and Ajax</title>
</head>

<body>

<h1>SimplePie Ajax Feed Demo</h1>
<h3>Digg</h3>

<div id="feedDiv" style="width:600px;height:200px;padding:1em;border:thin solid black"></div>
<div id="countDownTimer" style="width:600px;height:1em;padding:1em;border:thin solid black"></div>

<script type="text/javascript" src="update_feed.js"></script>

</body>
</html>

The javascript source code:

/**
 *
 * Update RSS/ATOM feed and display it using SimplePie and Ajax
 *
 *
 * LICENSE: This source file is subject to the BSD license
 * that is available through the world-wide-web at the following URI:
 * http://www.opensource.org/licenses/bsd-license.php.
 *
 * @author     Michael P. Shipley <michael@michaelpshipley.com>
 * @copyright  2008 Michael P. Shipley
 * @license    http://www.opensource.org/licenses/bsd-license.php BSD
 * @version    1.0
 * @link       http://www.michaelpshipley.com Michael Shipley
 */

/*
	Global variables
*/

// Set ajax update interval
var minutesBetweenUpdates = 1;

// Set feed url
var feedUrl = 'http://digg.com';

// Set url of PHP script that will fetch and return a feed or feeds using SimplePie
var scriptUrl = 'http://localhost/update_feed/update_feed.php';

// Set SimplePie cache duration (seconds)
var cacheDuration = 0;  // normally 3600

// Set div id where feed output will go
var divId = 'feedDiv'; 

/*
	Initialize feed display
*/
updateFeed(feedUrl,scriptUrl,cacheDuration,divId); 

/*
	Start feed update timer
*/

// Calc milliseconds
var seconds = minutesBetweenUpdates * 60;
var milliseconds = seconds * 1000;

// Setup function that feed update timer will call
var command = 'updateFeed(feedUrl,scriptUrl,cacheDuration,divId)';

// Start feed update timer
var updateFeedTimer = setInterval(command,milliseconds);

/**
	Use ajax to call  SimplePie to get feed data
	@param: feedUrl  string  feed link
	@param: scriptUrl string php script url
	@param: cacheDuration integer SimplePie cache duration in seconds
	@param: divId string id of div to output html to
*/
function updateFeed(feedUrl,scriptUrl,cacheDuration,divId)
{
	// Display the "updating" message
	var div = document.getElementById(divId);
	div.innerHTML = div.innerHTML + '<p>Updating...</p>';

	// Get the http requester
	if (window.XMLHttpRequest)
	{
		var http = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		var http = new ActiveXObject('Microsoft.XMLHTTP')
	}
	else
	{
		alert('browser doesn\'t support javascript http connections');
		return true;
	}

	// Process response
	http.onreadystatechange = function()
	{
		if(http.readyState == 4)
		{
			if(http.status != 200)
			{
				alert(http.responseText);
			}
			else
			{
				div.innerHTML = http.responseText;
			}
			return true;
		}
	}

	// Send http request via post
	params = 'url=' + feedUrl + '&cacheduration=' + cacheDuration;
	http.open("POST", scriptUrl, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.send(params);
	return true;
}

/*
	Start countdown timer (optional)
*/
var countDownTimerDivId = 'countDownTimer';
var date = new Date();
var timeOut = date.getTime() + milliseconds;
var timerId = document.getElementById(countDownTimerDivId);
var timer = setInterval(countDownTimer,100);
function countDownTimer()
{
	var date = new Date();
	var timeLeft = timeOut - date.getTime();
	if(timeLeft <= 0)
	{
		timeLeft = 0;
		timeOut = date.getTime() + milliseconds;
	}
	timerId.innerHTML = 'Seconds to next update: ' + parseInt(timeLeft/1000);
}

The PHP source code

<?php

// turn off browser caching (required to make AJAX work)
header("Cache-Control: no-cache, must-revalidate");
header('Pragma: no-cache');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past

// retrieve POST parameters
$url = strip_tags($_POST['url']);
$cacheDuration = strip_tags($_POST['cacheduration']);

require 'simplepie.inc';
$feed = new SimplePie();
$feed->set_feed_url($url);
$feed->set_cache_duration($cacheDuration);
$feed->init();

if($feed->error())
{
	echo '<p>'.$feed->error().'</p>';
}
else
{
	foreach($feed->get_items(0,3) as $item)
	{
		echo '<a href="' . $item->get_link() . '">' . $item->get_title() . '</a>';
		echo '<br>';
		echo '<small>'.$item->get_date().'</small>';
		echo '<br>';
		echo '<br>';
	}
}
?>

6 Responses to “How to Display RSS or ATOM Feeds Without Re-Loading the Web Page Using Javascript, AJAX, and SimplePie”

  1. Davide on 27 Sep 2008 at 2:56 am #

    great tutorial! what if i’m trying to pull different information (and having different layout from each of the feed?

  2. Whoila Blog » Blog Archive » Great tutorial on display RSS feed using SimplePie and AJAX on 07 Dec 2008 at 4:52 pm #

    [...] Shipley has a great tutorial on AJAX + [...]

  3. gabusingh on 27 Jan 2009 at 10:13 am #

    i got this error but my cache folder is ok when i use other demos

    ./cache/6fc7571c2f3dfe23d10a16b5a9629a1c.spc is not writeable in F:\xampp\htdocs\p_test\1.1.3\simplepie.inc on line 1773
    …..
    and my bookmark system is not working properly ..

  4. gabusingh on 27 Jan 2009 at 10:20 am #

    how can i set here $feed->set_cache_location ();

  5. Heiko on 10 Mar 2009 at 10:12 am #

    In Version 2 the countDownTimer is missing…

  6. Projektvorstellung: MC Tweets « webserviceXXL on 12 Mar 2009 at 7:01 am #

    [...] Feed Reload von Michael Shipley Ein einfaches Script, dass es ermöglicht in Kombination mit SimplePie einen Feed zu cachen und über AJAX die angezeigten Tweets nach einer bestimmten Zeit automatisch zu aktualisieren. [...]

Trackback URI | Comments RSS

Leave a Reply