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.


Comments

sln @ 5th Apr 2009

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 @ 5th Apr 2009

@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 @ 11th Jul 2009

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 @ 11th Jul 2009

@janani

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

Duncan @ 28th Jul 2009

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 @ 28th Jul 2009

@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 @ 27th Oct 2009

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 @ 8th Jan 2010

Here is a good website to help you format dates using the mysql date_format function.

Kai @ 23rd Jan 2010

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 @ 23rd Jan 2010

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).'

squirrel @ 4th Mar 2010

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 @ 10th Jun 2010

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 @ 16th Jun 2010

Really Gr8 Stuff man
Thank you So much
Proud to be a Programmer
Gr8 Success

mauritius holidays @ 28th Sep 2010

You have written a very informative post. I came across your blog via google.com by searching relevant information. I have bookmarked your site and sent the link to sme of my colleagues are will also find that useful.

Muharrem @ 23rd Nov 2010

I Wanna ask question about UTF-8 to ISO-8859-9 character convert, i found rss fetch this problem solved with iconv php function but, i cant recognize your code with iconv.

How can i solve turkish iso-8859-9 character problem on my rss feed?

thanks

Muharrem @ 23rd Nov 2010

I'm sorry to post more than one problem figured out you can delete my messages

EasternEuropeans @ 28th Dec 2010

I am going to give this a go on our articles section www.easterneuropeans.co.uk/articles without getting our programmer involved and costing me more money!! I will report back and see if it helped me or not. I do thinks it is well laid out and simple at least to copy and paste(which i am great at)

voxsar @ 25th Jan 2012

Hey this RSS is suppose to update and show in realtime, right? so how come when i add a record to mysql, the i have "refreah" page to reflect the update should'nt it update on it own?

Real time syndication right? we are talking the same topic, i guest i'll have to use http equve refresh for it auto part of your RSS

Salman Ali Khan @ 6th Mar 2012

Nice post. before this i got the script from another site and that was not working. thanks to you to share the script and i implemented it in my website www.businefieds.com/rss/

Aneeq @ 23rd Apr 2012

There are several ways to read RSS feed in PHP, but this one is surely one of the easiest.

channel->item as $entry) {
echo “link’ title=’$entry->title’>” . $entry->title . “”;
}

?>

Source:
http://phphelp.co/2012/04/23/how-to-read-rss-feed-in-php/
OR
http://addr.pk/a0401

undeadshand @ 1st Jun 2012

Hi there,i need some assistance. how to make RSS reader, which takes the XML file with a list of addresses and fulfills select feeds (option) box to the addresses.

By selecting a specific address, broadcast content RSS on the card is located.

i made the reader but im stuck i can't understand the next steps.i am a beginner at programing so any help would be nice.

thanks in advance!

vicos2 @ 10th Jul 2012

can i add some image in the descriptions? how?

saad @ 27th Jul 2012

my hosting account is automatically deleting .rss feed file... :-(((

تعبیر خواب @ 15th Apr 2013

thanks ... Nice post !

managers @ 15th Apr 2013

my hosting account is automatically deleting .rss feed file.... Oh my god

Grace @ 8th Jan 2014

$row[formatted_date] doesn't display anything on mine :(

Len Farneth @ 6th Apr 2014

Thank you! Of all the searching I did this was the first php data to xml tutorial I could make work! I did have to tinker a bit and rewrote the queries using mysqli, But the basic principles worked perfectly. Also I found I have to string replace "&" with "and" or the whole thing breaks if a story contains an "&".

As for the time functions I went with the following:

$pubDate=date(DATE_RSS, strtotime($row['log_time']));

I removed the GMT and it shows the exact local time of the entry, which works for me because 90% of my traffic is local and my rss gets about 30 or more entries per hour.

'.$pubDate.'

I look forward to tinkering around with dynamic category feeds ( I have a bunch)

Thanks for the great tutorial.

Woondinty @ 11th Apr 2014

When the leader focuses more on people, the lower they are, then the performance increases. It can support somebody who has 20lbs to eliminate and also provides a number of advanced techniques for a female that solely needs to lose 5-10lbs. Price (Deconstructing Jesus) and neuroscientist Sam Harris (The End of Faith). [url=http://www.cheapnfljerseychinashop.us.com/]Cheap NFL Jersey China Shop[/url]. Watch this ads on facebook presentation for far more understanding.eighteen. Now after thats finished, you can start with your outline before actually doing any article writing.Factor 4: Economy along with other DisordersEKG Technician SalaryThere are specific things which have been way past our reach and we can do very little but endure their results. Any lead may give you information about their company size, industry segment and their job title. This is simply because hair is conceivably a person of the most defining components of a girl, in conditions of private fashion and femininity. Js (javascript) as external files. Now days,[url=http://www.cheapnfljerseychinashop.us.com/]cheapnfljerseychinashop[/url], online coupons have now solve the problem of bargaining.[url=http://www.cheapnfljerseychinashop.us.com/]Wholesale Jerseys China[/url]. It can create stunning panoramic views without the need for stitching or using a distorted fish eye lens. So, figure out your investing shelling out spending budget and start to look for furnishings that falls inside your paying budget.

Add a Comment

required
required, but not shared

© 2014 Supadupa Web Design