I’ve recently updated my homepage to better reflect my online presence. It now mostly consists of a bunch of RSS feeds for the sites I interact with.
It turns out that rolling your own RSS reader is really simple, so long as you have PHP5 with the handy ‘SimpleXML’ extension.
I’ve written a quick little function you can plug into any webpage to grab an RSS feed and display it. The function takes two parameters, the URL of the feed and the number of items you want to display. It puts each news item in its own div so you can format it how you want with a little CSS.
Here’s the function listed below. It’s fully commented, so you can just paste it into a page of your own (or use an php ‘include’ to add it) and call it whenever you need to display a feed.
<?php
//Call this function using the following example:
//$feed = getNews("http://domain.com/rssfeed", 5);
function getNews($site_url,$n){
try{
// create a new cURL resource
$ch = curl_init();
//Set useragent (need this for Digg to let us view it)
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0
(Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9)
Gecko/20071025 Firefox/2.0.0.9');
//Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Follow any "Location: " header that the server sends
//as part of the HTTP header
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//Set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $site_url);
//Execute the fetch
$data = curl_exec($ch);
//Close the connection
curl_close($ch);
// Create an XML object
$sxe = new SimpleXMLElement($data);
} catch (Exception $e){
$Content = '<p>No RSS Feed available at the moment.</p>';
}
// Loop through the number of items specified in the call
for ($i=0;$i<$n;$i++){
$title = $sxe->channel->item[$i]->title;
$link = $sxe->channel->item[$i]->link;
//format the URL
$url = "<a href = '" . $link . "'>" . $title . "</a>";
$desc = $sxe->channel->item[$i]->description;
//Format each post with a div of its own
$Content .='<div class = "post">';
$Content .= "<h3>$url</h3> <p>$desc</p>";
$Content .='</div>';
}
return $Content;
}
?>
That’s it. Take it and liven up your pages with a little dynamic content.





