RSS - Creating a Feed (Part 3/3)

Friday, April 6th, 2007

In the final article of this series we’re going to write a script in PHP that will dynamically create an RSS feed from entries in a MySQL database.  If you decide to use this script in your own custom application, you may need to change parts of the script, such as the query.  You can check out the script here.

Let’s take a look at the script to see how it works.

The first part will define some parameters to establish a database connection.  This includes information such as the host, username, password, and the database.

This next part is important.

header(’Content-type: text/xml’);
print “<?xml version=\”1.0\”?>\n”;

This sends the appropriate header information to the client telling it that this is in fact an XML file. Without this line, your feed will show up as plain text and will be read as such.

After the header information, we begin the actual RSS feed. This should look familiar as it was covered in the previous article. Simply fill this information out as it relates to your site or have it retrieve the information from another source, such as your database.

<?php
 // Connection to db
 $mysqldb = new mysqli(HOST, USER, PASS, DB);
 // Query to select posts

 $query = “SELECT * FROM posts”;
 $result = $mysqldb->query($query);
 if($result->num_rows) {
  while($row = $result->fetch_array(MYSQLI_ASSOC)) {
?>

   <item>
    <title><?php echo $row['post_title']; ?></title>
    <link><?php echo $row['post_link']; ?></link>
    <author><?php echo $row['post_author']; ?></author>
    <description><?php echo $row['post_content']; ?></description>
   </item>
<?php 
  }
 }
?>

This is the part of the code that fetches the posts from the database and turns them into the RSS feed. Simply retrieve all of your posts from the databse and use a while loop to print them all out as items of the feed. Once the loop is done, close the channel and RSS tags and you’re done!  You now have an RSS feed that will update itself when you update your MySQL database.

One Response to “RSS - Creating a Feed (Part 3/3)”

  1. ExtraLabs Feed Editor is very useful for making RSS.

    Dmitry

Leave a Reply