Jordi Boggiano

Jordi Boggiano Co-Founder of Private Packagist – Dev at TeamupComposer lead – Wandering Belgian – Speaker

Blog RSS Feed Twitter @seldaek

RSS Generator

Categories

RSS Generator

Object Oriented approach to generating RSS feeds

These two classes allow you to build a RSS 2.0 feed quite easily. Most available PHP RSS Feeds builders I had a look at are array-based and I think it's cleaner to use a full object oriented approach as it allows you to enforce a structure and rules in a easier manner, so I decided to do my own version of it.

Full documentation is included with the sources archive.

Implementation example

<?php 
    // create the feed instance 
    $feed = new RSSFeedGen('My Feed', 'The best stories of my life', 'http://mysite.com'); 
    // set some additional properties to it 
    $feed->webMaster = "me@mysite.com"; 
    // get the last 10 articles and loop over them 
    $articles = mysqli_query('SELECT id, date, title, summary FROM articles ORDER BY date DESC LIMIT 10'); 
    while($article = mysql_fetch_assoc($articles)) 
    { 
        // creates a new feed item for every article, load settings in it (they can all be set by the constructor or indepently, as you prefer) 
        $item = new RSSFeedItem($article['title'], $article['summary'], 'http://mysites.com/articles.php?id='.$article['id'], $article['date']); 
        // adds the item to the feed 
        $feed->add($item); 
        // check if the feed has a last generation date already, if it's empty set it to the last article published 
        if($feed->lastBuildDate == null) 
        { 
            $feed->lastBuildDate = $article['date']; 
        } 
    } 
    // now we are happy, we can save it somewhere 
    // if it's generated when a new article is posted using: 
    $feed->save('feeds/stories.xml'); 
    // or if it's generated on the fly by a php page, just output it and die 
    // so nothing else troubles the XML formatting 
    $feed->output();

Requirements

  • PHP5 (PHP5.2 or superior recommended but it should run on lower versions)

DownloadDownload

Last updated on : 02/02/2008, Posted in PHP