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.

You Might Also Like...

Share the Love

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

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

mauritius holidays @ 28 Sep 2010 07:39:11 AM

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 @ 23 Nov 2010 06:56:33 PM

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 @ 23 Nov 2010 07:34:29 PM

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 @ 23 Nov 2010 08:23:42 PM

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 @ 23 Nov 2010 09:56:00 PM

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 @ 23 Nov 2010 09:57:35 PM

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

EasternEuropeans @ 28 Dec 2010 08:48:01 AM

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)

oxydayfoelype @ 5 Jan 2012 02:06:06 AM

lTtwPyrTx ugg boots outlet tXprFwsLj http://peternorthcott.com

TugChoodo @ 5 Jan 2012 02:08:10 AM

All of their own clients simply can purchase 1 item for every [url=http://www.bouisvuittonsneakers.350.com/]louis vuitton sneakers[/url] kind to be able to allow some other clients purchase just about all for just one kind.
Those who find themselves buying a great best [url=http://sunglassesab.webs.com/]sunglasses[/url] brand name in fashion will not need to move further and will utilize our own attached web site to obtain the many traditional bags with a very well low price.
So if you want to current a gift to any of your relatives then give [url=http://ahanelsunglasses.yolasite.com/]chanel sunglasses[/url].
[url=http://bhanelflats.yolasite.com/]chanel flats[/url] fulfills exactly what these people desire inside a actual identification.
consequently should your [url=http://aouisvuittonshoesformen.webs.com/]louis vuitton shoes for men[/url] features sloping as well as block images or possibly a seam towards bottom level and then the idea no initial.
Additionally, [url=http://bhanelwallets.yolasite.com/]chanel wallets[/url] offers all of us along with nemrous style great banquets, which all of us loved ourself greatly.
Within 1957 in the Style Honours within Dallas, Tx,[url=http://ahanelbag.webs.com/]chanel bag[/url] Springtime selection was handed the style Oscar and also the style globe known as Coco the most crucial creator from the 20th hundred years.
Bags coming from [url=http://ahanelsunglassesonsale.yolasite.com/]chanel sunglasses on sale[/url], even as already know just, are constructed of the best possible buckskin proven to humankind and also most of the time, appear built with a free of charge airborne dirt and dust carrier at the same time.

voxsar @ 25 Jan 2012 08:04:03 AM

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 @ 6 Mar 2012 12:33:18 PM

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 @ 23 Apr 2012 04:02:06 AM

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 @ 1 Jun 2012 03:05:51 PM

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 @ 10 Jul 2012 06:19:13 AM

can i add some image in the descriptions? how?

saad @ 27 Jul 2012 06:57:51 AM

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

leaplecon @ 4 Oct 2012 12:42:01 AM

[url=http://badcreditpaydayloanonlinehere.com/#24310]online payday loan[/url] - payday loan online , http://badcreditpaydayloanonlinehere.com/#10365 payday loan online

bloormMemodom @ 17 Oct 2012 03:02:00 AM

Uvbklv louis vuitton sac Wfxymw http://louisvuittonr.monwebeden.fr/
Mnbdvb burberry outlet Zanmzb http://burberryoutletj.webeden.co.uk/
Hsleqn uggs outlet for kids Fehrun http://uggsoutletu.webeden.net/
Gqcxvl ugg boots on sale usa Mdlnrj http://uggbootsonsalem.webeden.net/
Yovcqe louis vuitton outlet Fwrslu http://louisvuittonoutletw.webeden.net/
Qugyfc ugg sale Gkilyc http://uggsalet.webeden.net/
Gowaab discount ugg boots online Ljieff http://discountuggsp.webeden.net/
Ibwqco wholesale nhl jerseys Jaqjja http://wholesalenhljerseysl.webeden.net/
Gyvwef christian louboutin uk sale Gdjinc http://christianlouboutinukl.webeden.co.uk/
Unhfbj beats by dr dre Sliqem http://beatsbydrdreg.webeden.co.uk/

HenueTofnox @ 23 Oct 2012 07:11:33 PM

Iqwxxl uggs clearance Pxvxuy clearance uggs Pwiwpq clearance ugg boots Ogmhuw http://clearanceboots.webs.com/
Kpkihc ugg boots on sale free shipping Wckubx ugg boots on sale Zskrnx uggs boots on sale Sgxtvs http://bootsonsalee.webs.com/

NarReotte @ 23 Oct 2012 11:03:37 PM

Gaszwi uggs outlet online Wtgahk uggs outlet store Wizbhm ugg outlet online Ojspzb http://fashionablebootsdiscount.webeden.net/
Tdsfee uggs nederland Lvizpw ugg Ydgkha uggs nederland Nplyuc http://relaxedbootsstore.webeden.net/

FerGerePreera @ 23 Oct 2012 11:46:32 PM

Bhgraq canada goose outlet Nkbbsk canada goose sale Byqxmd canada goose jacket Dfuswn http://www.parkasale.us/

psyptohobby @ 24 Oct 2012 12:54:50 AM

Vrizuu ugg boots sale Oxwexm ugg boot sale Ylajqu ugg boots sale Adyfuz http://comfortablehoesg.webeden.net/
Acwjyv uggs uk online Nqtuei uggs uk online Hczhww ugg uk Difzjf http://cozyubootsuk.webeden.co.uk/

HenueTofnox @ 24 Oct 2012 12:59:20 AM

Cwrxnk uggs uk sale Vqlyxc ugg uk Eqndlw uggs uk Eawdaa http://ugguka.moonfruit.com/
Vizqfs genuine ugg boots Axfpkp ugg boots sale Mjktwp genuine ugg boots Wxynpi http://uggbootssalee.moonfruit.com/

duroPalvalo @ 24 Oct 2012 06:58:16 AM

Hwbjuk ugg clearance Rbwbel ugg boots clearance Znnyik ugg boots clearance Xedjls http://www.getclickshere.com/

HenueTofnox @ 24 Oct 2012 11:30:57 AM

Xiyvkr cheap ugg boots uk Fnpwew ugg boots uk stockists Wskufy ugg boots uk cheap Qlzoum http://uggbootsuka.moonfruit.com/
Amfpzp ugg sale usa Urjpfu ugg sale Hjpnlz uggs sale Swsfam http://salekidsfd.webs.com/

Bestdiece @ 24 Oct 2012 12:24:48 PM

Fpnbep beats by dre solo Bvcjwc beats by dre solo hd Xgznlg beats by dre solo Syvsdj http://cheapbeatsbydresheadphonesus.info/

kmwbyyaw @ 24 Oct 2012 01:03:50 PM

[url=http://www.canadagoosefranceoutlet.fr]canada goose trillium[/url] [url=http://www.norgecanadagoosejakker.eu]2012 Canada Goose[/url] He has been rumored to be potentially signing with Atlant Moscow Oblast of the Kontinental Hockey League, of whom he formerly played with in 2006-07.
http://www.norgecanadagoosejakker.eu The Grand Pacific Railroad also wanted to buy land to build a town in the area but the only piece of land was owned by the First Nations Indian band called the Lheidli T'enneh..

GodaAreda @ 24 Oct 2012 02:20:39 PM

dxunx Moncler Pas Cher ucooq http://www.doudounemonclervb1.com/
wasbz North Face Sale jmihv http://www.thenorthfaceoutletq.com/
gkser Doudoune Moncler Pas Cher etqir http://www.doudounemonclervb1.com/
jtsms North Face Outlet UK tjgtq http://www.thenorthfaceoutletq.com/
ofcjt http://www.doudounemonclervb1.com/ dafzn http://www.doudounemonclervb1.com/
http://www.thenorthfaceoutletq.com/

nplmnkyo @ 14 Nov 2012 08:00:06 PM

Mid Wales - I don't understand why being so skinny is promoted as good. ugg classic short
canada goose jacket canada goose coats cheap buy canada goose in canada
canada goose snow mantra Mlurjhvue Canada Goose Langford Parka

LuckyCoder8 @ 1 Mar 2013 03:07:42 PM

Thanks, It was a very interesting reading, I will enjoy the time that its gonna be of use :) soon enough!

Giannis @ 23 Mar 2013 04:17:10 PM

Nice post.... I think you have forgot the database connection code from above...

Thank you

تعبیر خواب @ 15 Apr 2013 09:39:12 AM

thanks ... Nice post !

managers @ 15 Apr 2013 09:41:30 AM

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

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 to Blog

RSS Email

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.

Subscribe by: RSS | Email
Copyright © 2013 Supadupa Web Design