Easy Dynamic RSS Feed in PHP/MySQL

Create an RSS feed that automatically gets the latest articles from your database in PHP and displays it in RSS syntax instantly.

RSS feeds are practically a requirement now days for websites. If you have any sort of news, tutorials, articles that are updated regularly, an RSS feed is a must have. We are going to show you how to create a dynamic RSS feed to updates automatically when you have added something to your website.

Database Requirements

The feed requires the following information for each post that will be added:

  1. Title
  2. Content or summary
  3. Web address to the article
  4. The date it was published

Provided that you have the required information in your database already, we can move on.

1. Add the RSS 'Header' Info

The first step is to tell the browser that this file is an XML file. If you didn't already know, RSS is an XML file that uses a special defined syntax. To let the browser know this is an XML file, we add the following line:

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

Now that we have told the browser that this is an XML file, we can start spitting out XML syntax for it to read. RSS has some 'Header' like fields to help define important variables about the entire feed:

echo '<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>My Website Name</title>
<description>A description of the feed</description>
<link>The URL to the website</link>';

Let's run through the lines added in the code above. The first line that starts with '<?xml...' is simply a line that tells the browser that we are starting the XML code, what version to use and how it is encoded. Pretty much standard stuff. The next line (<rss...) tells the browser what version of rss we are using (in this case its 2). Then we start with <channel>. This is like <body> in HTML. It tells the browser 'Here comes the important information about this feed and its contents'. The <title> tags contain the title of the feed such as 'My RSS News Feed'. The <description> tags contain information about that describes the feed such as 'The latest news from my website'.  Finally, the <link> tags contain the full URL to the website. All this information is pretty much required and is often used on other websites to display the RSS feed.

2. Adding Articles to the Feed

Time for the dirty work. RSS feeds usually contain between 10-15 of the latest content on a website. So in this case, we are going to grab out the latest 15 articles from the database and display them in RSS XML:

$get_articles = "SELECT id, title, summary, 
DATE_FORMAT(added_date,'%a, %e %b %Y %T') as formatted_date 
FROM articles ORDER BY added_date DESC LIMIT 15";

$articles = mysql_query($get_articles) or die(mysql_error());

while ($article = mysql_fetch_array($articles)){
      
    echo '
       <item>
          <title>'.$article[title].'</title>
          <description><![CDATA[
          '.$article[summary].'
          ]]></description>
          <link>http://www.mysite.com/article.php?id='.$article[article_id]</link>
          <pubDate>'.$row[formatted_date].' GMT</pubDate>
      </item>';
}

First, we write our query to get our articles. I have ordered by the date field descending to get the latest articles. I have also formatted the date using DATE_FORMAT() to convert the date field into a style that RSS likes. We then run the query using mysql_query() and die with an mysql_error() if there is an error.

We then do a while loop using mysql_fetch_array(). This will run through all the records retrieved and execute the code within the while loop for each record. In this loop we echo the structure of an RSS feed item. Firstly, we define the item with <item>. We then add the title of the article into the <title> tags. The <description> tags contains the summary or the full article. It is important that you wrap your description information with <![CDATA[ and close it with ]]>. This is to prevent any possible breakage if you have some HTML code within your description. The <link> tags provide a link to the article's web page and <pubDate> provides the date the article was added to the website.

All this information is required. 

3. Closing the RSS Feed

Now that we are done adding the articles to the feed, we need to close the RSS feed to let the browser know that there is no more content on the feed. We do this by adding the following lines after the loop:

echo '</channel>
</rss>';

The lines above close the <channel> and <rss> tags to finish off the feed.

4. The Full Source

That is pretty much it! You can do alot of other things, just have a look at what other people use in their RSS feeds to get an idea. So, here is the full code:

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

echo '<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>My Website Name</title>
<description>A description of the feed</description>
<link>The URL to the website</link>';
$get_articles = "SELECT id, title, summary, 
DATE_FORMAT(added_date,'%a, %e %b %Y %T') as formatted_date 
FROM articles ORDER BY added_date DESC LIMIT 15";

$articles = mysql_query($get_articles) or die(mysql_error());

while ($article = mysql_fetch_array($articles)){
      
    echo '
       <item>
          <title>'.$article[title].'</title>
          <description><![CDATA[
          '.$article[summary].'
          ]]></description>
          <link>http://www.mysite.com/article.php?id='.$article[article_id]</link>
          <pubDate>'.$row[formatted_date].' GMT</pubDate>
      </item>';
}
echo '</channel>
</rss>';
?>

Let us know how you get on with this tutorial by using the comments below.

Share the Love

If you liked this post, why not share it with others?

Make money on your website, quickly and easily.

Comments

sln

5 Apr 2009 12:46:58 PM
We're living in world of many languages, so ISO-8859-1 encoding is not very clever for use. For example I'm from Poland, an we have some special chars in our alphabet. So, as I thing, better way to do this is to use UTF-8 encoding. Using it language makes no difference.
Next, You are proposing to use echo for makeing XML DOM structure. You're building websites since 1996 so You know, that we can operate on XML using PHP with SAX parser, the DOM, SimpleXML, XMLReader, XMLWriter, and the XSLT processor. SimpleXML is very easy, an much more faster, because of XPath support.
Probably for some begginers using just arrays would be faster, and much more easy to understand. But as I think, this method sould be only shown to introduce the way RSS works, and can be used. But, after all more useful methods should be represented.
Best regards
Robert

David

5 Apr 2009 01:41:05 PM
@sln Thanks, Robert, for your comment. Good point about choosing the correct type of encoding.

This tutorial was built to provide a quick and easy way to create an RSS XML feed. Yes, there are more advanced ways to do it which might provide even more flexibility, but for the case of building a standard RSS feed, I believe that keeping it simple is important.

I might consider adding some tutorials in the future regarding the more advanced ways of building and parsing XML using PHP.

Thanks,
David

janani

11 Jul 2009 03:14:07 AM
I try this code but I get an error like that , Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in on line 11 How can rectify this?

David

11 Jul 2009 04:07:48 AM
@janani

That error usually means that you forgot to add a ';' at the end of one of your php lines.

Duncan

28 Jul 2009 01:26:04 PM
I tried this, but I get the error: XML Parsing Error: unclosed token
Location: http://www.greatwhiteparts.com/rss2.xml
Line Number 29, Column 7:';
------^

I tried a similiar code before and got the same type of error. Any suggestions?

David

28 Jul 2009 01:31:08 PM
@Duncan

From what it looks like, you need to tell your web server (apache or iis) to use PHP to process XML files. A quick google will find you an answer on how to add this into your .htaccess file.

OR, if you don't want to go that route, you can mask it with the following .htaccess line:

Rewriterule ^rss2.xml rss2.php [L]

That line tells Apache to use rss2.php when someone tries to visit rss2.xml. All you have to do is make sure the actual file is rss2.php or you will get a 404 error.

Craig

27 Oct 2009 12:21:27 PM
I\'m dying on this. I\'ve tried many tutorials and many methods and all have failed. I think this one is the closest I\'ve gotten to a successful RSS feed. I get a whole host of errors when I try to validate:

line 6, column 54: Undefined channel element: br (4 occurrences) [help]

http://www.craiggreenwood.com/journal.php ^line 7, column 0: Undefined channel element: b (6 occurrences) [help]

Warning: mysql_query() [function.mysq ...line 7, column 14: Unexpected Text (7 occurrences) [help]

Warning: mysql_query() [function.mysq ... ^line 7, column 32: Undefined channel element: a (2 occurrences) [help]

Warning: mysql_query() [function.mysq ... ^line 10, column 0: XML parsing error: :10:65: no element found [help]

Access denied for user \'craiggr\'@\'localhost\' (using password: NO)

Those are the error messages. Other tutorials require a connection to mysql_connect.php but this one doesn\'t. I don\'t get that. Obviously I have changed the code to match my databases and I\'m sure that\'s what breaking it. Can you offer advice on what I can do about this?

mysql format date

8 Jan 2010 04:07:46 PM
Here is a good website to help you format dates using the mysql date_format function.

Kai

23 Jan 2010 12:43:16 AM
I am trying to accomplish this using your script above with a few modifications. I am stuck on the date stuff. It displays the rows up to the date and then nothing else.

Can you help me get this to display correctly?

Thanks,

Kai

Here is how I am storing the date in the db:

`date` datetime NOT NULL default '0000-00-00 00:00:00',

Here is the php I have so far:

]]>
http://www.mywebsite.com/news/
'.date('F, j, Y \a\t g:i A, T', $row_date).'
'.$row['author'].'
';
}
echo '
';
?>

Kai

23 Jan 2010 12:44:56 AM
Oops! The date stuff should be displayed like this:

$row_date = strtotime($row['date']);
'.date('F, j, Y \a\t g:i A, T', $row_date).'

Gerard

28 Jan 2010 08:07:19 AM
The http://www.mysqlformatdate.com website is good for formatting the date

Gerard

28 Jan 2010 08:07:52 AM
sorry http://www.mysqlformatdate.com

squirrel

4 Mar 2010 11:22:45 AM
You have forget .' concatenation lines 24 :

example bad :
http://www.mysite.com/article.php?id='.$article[article_id]

example good :)

http://www.mysite.com/article.php?id='.$article[article_id].'

Thank you !

Boo

10 Jun 2010 03:25:56 AM
Hi David,

Thank you for your post, I managed to create the xml sitemap for my site.
This was really helpful and you comments are just as much : )
you are a legend!

kaviarasan

16 Jun 2010 12:13:34 PM
Really Gr8 Stuff man
Thank you So much
Proud to be a Programmer
Gr8 Success

Leave a Comment

Name (Required)
Email (Required, but not published)
Website
Comment
Get emails when comments are added. (You can stop emails at any time)

Want an Avatar? Get one at http://www.gravatar.com

Subscribe

Get instant updates.
Subscribe by: RSS | Email

Your Ad Here

About the Author

David

Hi, i'm David! I've been building websites since 1996. Through my experiences, I have gained a well-rounded knowledge of the design & development of websites. I founded Supadupa Web Design to help others learn from my experiences.

Follow me on Twitter