Cover Image

For most, adding an RSS feed to their website is simply a matter of writing a simple xml file. But what if your site is dynamically generated via PHP and a mySQL database. Do you really want to have to edit the XML file every time you add new content? Of course not! Here I explain how to use PHP to generate an RSS feed for your dynamic website.



First off, I'm assuming that you have some sort of mySQL database set up and filled with content. If you do, great. Now, lets get started.

The XML behind an RSS feed is very simple. If you don't know XML but you have experience with HTML, then this should be easy for you to understand. Let's start off by explaining the structure of an RSS feed. Here I'm using faux information, but you should replace everything like titles, usernames, and passwords to your own.

    
    
    

    Title of your RSS feed
    Description of the contents of this RSS feed
    http://yourdomain.com/
    Copyright Information

    
        Story Title
        Summary of story content goes here.
        http://yourdomain.com/urlToArticle.html
        http://yourdomain.com/urlToArticle.html
        Wed, 4 Oct 2006 19:30:00 EST
    

    
    

    


From top to bottom, we're defining that this file is XML, then telling the broswer that it's an RSS 2.0 file. Next we open the channel and describe what the RSS feed is all about. After that we have our story information. The and here are the same because both are meant to link to the article. Most aggregators use the information to link to the article (makes sense enough), however some will also use the as a way to uniquely identify each item, just incase the tags for each item just take you to the index page rather than the article. I think it's silly and redundant, but you will need to validate. As you can also see, the is formatted in UNIX timecode. This will become important later on when we insert our date-type mySQL data. Next we're going to add PHP to make it more dynamic.

             header('Content-type: text/xml');
        mysql_connect('localhost', 'username', 'password');
        mysql_select_db('database_name');
    ?>

This goes at the very top of your file, replacing the "". It makes PHP tell the browser that the file being generated is an XML document. It's needed because if you kept the old line, the PHP parser would never get past the first line, thus returning no data to the user. Also, here we will place our connection string for the database. You can use an include() statement here for security purposes if you wish. Next, we're going to replace everything inside of the tag with new, pretty PHP.

    
    $sql = "SELECT id, title, UNIX_TIMESTAMP(date_posted) AS date_posted, summary ";
    $sql .= "FROM news ";
    $sql .= "ORDER BY date_posted DESC";
    $sql .= "LIMIT 15";

    $result = mysql_query($sql);

    while($row = mysql_fetch_assoc($result)) {
        $id = $row['id'];
        $title = $row['title'];
        $date_posted = $row['date_posted'];
        $summary = $row['summary'];
    ?>
        
            <?php echo htmlentities(strip_tags("$title")); ?>
            
            http://joshuatreedesigns.com/jtd/post.php?id=
            http://joshuatreedesigns.com/jtd/post.php?id=
            
        

    

If you're a little confused here that's OK. First off, we're setting our SQL query that will return rows from the database. As you can see, the UNIX_TIMESTAMP is setting my date_posted value to the unix format which is needed for the RSS feed. I'm also limiting the items to just the most recent 15. Next we run the query and store the result as an array.

The while loop is perfect for this sort of catching and organizing of data. Here we're running a while loop for each value ($row) of the $result array. As you can see, we're also echoing the values from each row into it's own set of XML tags. The different functions being implemented in the echo tag, again, are for the results to produce a valid RSS file as it cannot contain special characters, but rather must be replaced with their html entities.

Lastly, don't forget to close the and tags. The final code will look something like this:

             header('Content-type: text/xml');
        mysql_connect('localhost', 'username', 'password');
        mysql_select_db('database_name');
    ?>

    
    $sql = "SELECT id, title, UNIX_TIMESTAMP(date_posted) AS date_posted, summary ";
    $sql .= "FROM news ";
    $sql .= "ORDER BY date_posted DESC";
    $sql .= "LIMIT 15";

    $result = mysql_query($sql);

    while($row = mysql_fetch_assoc($result)) {
        $id = $row['id'];
        $title = $row['title'];
        $date_posted = $row['date_posted'];
        $summary = $row['summary'];
    ?>
        
            <?php echo htmlentities(strip_tags("$title")); ?>
            
            http://yourdomain.com/news.php?id=
            http://yourdomain.com/news.php?id=
            
        

    

    
    

I suggest naming this file index.php and putting it into a sub-directory of you website named "rss". This will make the next step a little easier.

If you want the RSS feed icon in Safari, or other aggregators to show up and notify users of the feed when they visit the site, be sure to add this line of code to the headers of your other web pages.

    

One last thing, before you take your feed "live" be sure to make sure it validates. An invalid feed can cause problems with aggregators and browsers. There are several web-based validation tools such as Feed Validator that make validation a snap.

Good luck and happy syndicating!