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

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 '' . "\n";
echo '' . "\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 '' . "\n";
echo '' . "\n";
echo 'A blog full of the finest 100% pure Jonnyisms' . "\n";
echo 'http://www.jonnyhope.co.uk' . "\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 '' . "\n";
    echo '' . "\n";
    echo '' . "\n";
    echo 'http://www.jonnyhope.co.uk/index.php?id=' . $post['id'] . '' . "\n";
    echo '' . $post['formatted_date'] . ' GMT' . "\n";
    echo '' . "\n";

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

echo '' . "\n";
echo '' . "\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 Friday 4th May 2018 at 8:46pm.

Tweet This or Share on Facebook