Easy Dynamic RSS Feed in PHP/MySQL
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:
- Title
- Content or summary
- Web address to the article
- 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.
You Might Also Like...
Share the Love
If you liked this post, why not share it with others?

Comments
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 AMThat error usually means that you forgot to add a ';' at the end of one of your php lines.
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?
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.
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?
Kai
23 Jan 2010 12:43:16 AMCan 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$row_date = strtotime($row['date']);
'.date('F, j, Y \a\t g:i A, T', $row_date).'
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 !



sln
5 Apr 2009 12:46:58 PMNext, 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