22
aug
2008

Creating RSS feeds with SimpleXML

I love RSS feeds. One just needs to take a look at my Google Reader to see that.

One of the best things about them is just how easy they are to make. Here is a quick example with PHP showing how you can create RSS feeds with the PHP5 module SimpleXML.

<?php

$items = array(
    array(
        "title" => "example", 
        "pubDate"=>2, 
        "link"=>"http://www.dougalmatthews.com"
        "description"=>"post content")
);

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

$rssName = "My RSS Feed";
$rssHomePage = "http://www.dougalmatthews.com/";
$description = "My RSS feed description";

$sxe = simplexml_load_string("<rss version=\"0.91\">
<channel>
    <title>$rssName</title>
    <link>$rssHomePage</link>
    <description>$description</description>
</channel>
</rss>");

foreach($items as $item){

    $child = $sxe->channel->addChild('item');
    $child->addChild('title', $item['title']);
    $child->addChild('pubDate', date(DATE_RFC822, $item['timestamp']));
    $child->addChild('link', $item['link']);
    $child->addChild('description', $item['description']);

}

echo $sxe->asXML();

It's as simple as that really. Above I've shown some sample data that's set at the top in an array. You can easily add to this or change the data source so it comes from a Database. This example of course has limitations as there is very little point creating a feed for static data.

There you go, add an RSS feed to your site today and send me the link so I can eventually aggregate the full internet! :)

I used this method to create a couple of RSS feeds. I created the data from scraping a number of websites. The feeds can be found here. I'll be posting up screen-scraping soon!

A very small piece of code that can prove to be very useful.

Short url - Related tags: aggregate, php, rss, simplexml

blog comments powered by Disqus