Creating a Dynamic RSS Feed with PHP

in Development at 12:00am with 0 comments.

This project has required me to learn how to write a RSS feed for the first time, and I of course want this feed to be automatically generated by PHP from the database of posts.  My successful attempt can be subscribed to at: www.jonnyhope.co.uk/rss. Check it out!

A quick run down of creating a PHP generated RSS feed

1. Begin by opening a php document in the usual way, and include your config information (for your database connection etc.) Set the Content-Type header as text/xml


include 'config.php';

header('Content-Type: text/xml');

2. Query the database to retrieve your posts, make sure to include the title and content and any information you need to create your link (in my case the post id is required in the link), also you need the date formatted as per the fomatting below. Don't forget to include only active posts and limit it to around 10 items.

$all_posts = $mysql->query("SELECT posts.id, 
                                   date_format(from_unixtime(posts.date_created),'%a, %e %b %Y %T') as formatted_date
                            FROM posts
                            WHERE posts.status = 'active'
                            ORDER BY posts.date_created DESC
                            LIMIT 0, 10");

3. Begin the XML output and the RSS section exactly as below.

echo '<?xml version="1.0" ?>' . "\n";
echo '<rss version="2.0">' . "\n";

4. Open a channel section and set the title, description and link of the RSS feed, the link should be an exact link to your website.

echo '<channel>' . "\n";
echo '<title>Jonny Hope</title>' . "\n";
echo '<description>A blog full of the finest 100% pure Jonnyisms</description>' . "\n";
echo '<link>http://www.jonnyhope.co.uk</link>' . "\n";

5. In a while loop, moving through the posts queried from the database open a new item section, in each item section set the title, description (content), link and pubDate of your posts, not forgetting to to wrap your content in CDATA tags to avoid problems of the code it contains breaking your RSS feed.

while($post = $mysql->fetch_assoc($all_posts)) {
    echo '<item>' . "\n";
    echo '<title>' . $post['title'] . '</title>' . "\n";
    echo '<description><![CDATA[' . $post['content'] . ']]></description>' . "\n";
    echo '<link>http://www.jonnyhope.co.uk/index.php?id=' . $post['id'] . '</link>' . "\n";
    echo '<pubDate>' . $post['formatted_date'] . ' GMT</pubDate>' . "\n";
    echo '</item>' . "\n";

6. Finally close the channel and rss sections of the XML document and last of all close your PHP document.

echo '</channel>' . "\n";
echo '</rss>' . "\n";


Good luck in writing your own RSS document!

This post was originally created on Tuesday 24th April 2012 at 12:00am and categorised under Development by Jonny Hope. It was last updated on Wednesday 2nd May 2012 at 11:03pm.

Tweet This or Share on Facebook