How to Create an RSS Feed for Your Site in PHP

Picture of a globe in front of a keyboard.Note: If you look around the site, you may have noticed that I haven’t updated this place in a long time. Check out my new project, which is more closely focused on photography. I still discuss some design issues, though, like these free InDesign templates. If you’re looking for a camera, check out this post on the differences between entry level Canon dSLR cameras.

Or, take a look at my photography studio’s website. Along with photography, we offer a handful of design and printing services, mostly for models, actors, and fashion designers. Our newest offering is the design and printing of modeling/acting comp cards, which start at $60 for a set.

Most blogging platforms come with built-in support for RSS feeds. Why? It’s a great way for users to keep up to date on your new content. Instead of loading up a dozen favorite sites, they can look at one feed reader and then decide what to pursue further.

So what if you don’t use a blogging platform or CMS that creates a feed for you? You can create one yourself in PHP. It’s pretty simple.

Elements of an RSS 2.0 Feed

There are pretty strict standards about RSS feeds – intended to make it easier for readers to parse and display the information. Before we dive into building a feed, we should look at what it should contain. You can read the full spec at feedvalidator.

An RSS 2.0 Feed is a special type of XML file. The first things you’ll need in your file is an xml declaration, and an opening/closing RSS tag. Like this.

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  //  Feed elements here
</rss>

Inside the opening rss tag, you can also include any namespaces that you’ll be using. That’s a bit more than we need to worry about at the moment, though.

Inside the rss tag, you need to create a channel tag. This holds all of the individual articles as well as some basic information about the feed. You’re required to create a title, link, and description tag. You can add a lot of optional tags, of which the lastBuildDate tag would be most useful.

A basic channel declaration would look something like this.

<channel>
   <title>My Wonderful Blog</title>
   <link>http://mydomain.com</link>
   <description>This is a feed of the latest articles at My Wonderful Blog.</title>
   <lastBuildDate>Thu, 14 Feb 2008 10:57:05 GMT</lastBuildDate>
 
   //  Include individual articles here
</channel>

Finally, you can include the individual articles inside of this channel tag. Each article is represented by an item tag and a series of optional tags. Some good tags to use for a basic feed would be title, link, description, and pubDate. Like this…

   <item>
      <title>My Latest Article</title>
      <link>http://mydomain.com/latestarticle.php</link>
      <description>This is the latest cool article at my wonderful blog.</description>
      <pubDate>Thu, 14 Feb 2008 10:57:05 GMT</pubDate>
   </item>
Using PHP to Create the RSS Feed

Now that we know what goes in to an RSS feed, we can worry about how to create one.

There are several approaches we can take here. We could have PHP dynamically output an RSS feed every time the file is accessed. We could create a SimpleXML object and write it to a file each time a new article is added. Or we could simply create a string and write it to an xml file.

We’ll take the third approach. This means we need to do three things.

  • Fetch the data from the database
  • Build the xml formatted string
  • Write the xml data to a file
Fetch the Data from the Database

This will vary depending on the database type you’re using and how it’s set up. If you’ve gotten this far in creating a dynamic, PHP-driven site, I’m sure you can figure out how to fetch information for your own database.

For the purpose of this tutorial, we’ll fetch information from a mySQL database. The database will hold the title, link, description, and pubDate of each article.

$query = "SELECT title, link, description, pubDate FROM
   articles LIMIT 10";
$result = mysql_query($query);

Note: I only retrieved the last 10 entries. There is no strict limit to the number of entries an RSS 2.0 feed can have, but it’s polite to leave it small. If they want to read every article, they’ll come to your site.

Building the XML Formatted String

Now, we need to create a blank string, format it like an XML file, loop through the mySQL result array, and insert the data into the XML file.

First, we’ll add the xml declaration, the rss tag, the channel tag, and the channel info. Then we can loop through the result set and create one item tag for each article.

$xmlString = '<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
   <title>My Wonderful Blog</title>
   <link>http://mydomain.com/</link>
   <description>Latest articles at My Wonderful Blog.</description>
   <lastBuildDate>' . date("D, d M Y H:i:s e") . '</lastBuildDate>
 
';
 
while ($row = mysql_fetch_array($result)) {
$xmlString .= '   <item>
      <title>' . $row['title'] . '</title>
      <link>' . $row['link'] . '</link>
      <description>' . $row['description'] . '</description>
      <pubDate>' . date("D, d M Y H:i:s e", $row['pubDate'] . '</pubDate>
   </item>
';
}
 
$xmlString .= '</channel>
</rss>';

Most of that should be self-explanatory. Where I added a newline before ending the string, I was simply adding white space to make the source code more readable. This isn’t necessary – but I like neat, readable source code.

$xmlString is being created in the beginning. Then, the additional strings are appended to it with the .= operator.

The one important thing to note here is date("D, d M Y H:i:s e"). This is PHP’s function to create a formatted date. The characters inside the string determine how the timestamp is formatted.

This format is the standard required by RSS 2.0 feeds. You could simply copy and paste this string to format your dates. “D, d M Y” creates something like “Thu, 14 Feb 2008.” “H:i:s” creates the time as “18:23:30.” “e” is a representation of the timezone – which should be GMT.

Write the String to an XML File

Finally, we need to write this string to an xml file. For simplicity’s sake, we’ll call this “feed.xml” and place it in the same directory as our script.

You could use a few functions to do the file-writing. In this case, file_put_contents would be simplest – all we need to do is dump the contents of the string into a file and overwrite any previous contents.

$filename = "feed.xml";
file_put_contents($filename, $xmlString);

Now you just need to incorporate this into your existing site. You could make this a standalone script and access it every time you add new content to your site.

Or, if you’re using some kind of home-brewed CMS, you could wrap this in a function and call it right after you save the content of a new article.

Besides creating a custom feed for your own website, there are some other uses for this. You could use it to create a feed of articles from diverse sources around the internet.

If you write at a variety of sites – like Helium, Associated Content, and Xomba – you can use this to create a unified feed. Or, you could create a feed of only select articles from one of those sources. You could also create a feed of simple data – not articles – like quotes, jokes, tips, etc.

Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , , , ,

33 Comments to “How to Create an RSS Feed for Your Site in PHP”

  1. Pages tagged "tutorial" said this on

    [...] bookmarks tagged tutorial How to Create an Web Cash Feed for Your Site in PH… saved by 5 others     mehrwish bookmarked on 02/15/08 | [...]

  2. Reza said this on

    It’s a very helpful post for creating rss in php. I like it most. Thanks for the tutorial :)

  3. Rajaie said this on

    Really simple and great tutorial!

  4. Katalog Stron said this on

    Simple but usefull!

  5. Lokesh said this on

    Just learning xml with php. awesome tutorial which I understood with no confusions. now can someone help me as to how could I incorporate this on any of the sites. any help would be highly appreciated – Lokesh

  6. RSS Feed: Building an RSS Data Feed in PHP with SimpleXML | Web Cash said this on

    [...] feeds are a must-have for modern websites. It’s easy enough to make an RSS feed of recent articles in PHP. But did you know an RSS feed can simply be information – not links to [...]

  7. Doony said this on

    If the link contain “&” it will be error. Also with bad character in the description. It should be parsing first.
    http://www.avun.com/rss/feed.xml

  8. Walkere said this on

    Never noticed that (I always used pretty URLs instead of ampersands in query strings).

    Ampersands aren’t acceptable characters for XML. Usually, ampersands in URLs are ignored, but apparently it breaks most feed readers and stops them from parsing the feed.

    Convert them to their html entity form – &amp;. You can do that quickly by using the htmlentities() function on the un-escaped string.

    There are still a few validation errors in your feed after that, but it will load properly (in Firefox) if you fix the ampersands.

  9. shialesh said this on

    hi I Place this code on my website but it give error

    http://feedvalidator.org/check.cgi?url=http%3A%2F%2Fwww.dogspot.in%2Fsyndication%2Ffeed.xml

    http://www.dogspot.in/syndication/feed.xml

    It is taking html tag as error .. can u please tell me how can i correct this

  10. Walkere said this on

    It seems that XML doesn’t like the entity reference &nbsp;. Try taking those references out and replacing them with regular spaces and see if the feed loads then.

  11. Tips to Ensure Your XML RSS Feed is Valid | Web Cash said this on

    [...] month, I wrote on article on creating an RSS feed for your site. Some people have reported problems with the process – but these all come from malformed XML, not [...]

  12. Andy said this on

    As RSS come in XML format, things become much simple if using native XML database/XQuery, that allows storing and processing your XML “AS IS”. Take a look at Sedna (www.modis.ispras.ru/sedna), it provides PHP API, very easy to start working with.

  13. Joe said this on

    You never closed the parentheses for the date() function in your while loop. Probably ends up an error.

  14. nude said this on

    linda blair nude

  15. nude said this on

    cindy crawford nude

  16. How to Create a Custom RSS Feed with PHP - Tutorial Collection said this on

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 8:10 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  17. Djoudi » How to Create an RSS Feed for Your Site in PHP said this on

    [...] How to Create an RSS Feed for Your Site in PHP Most blogging platforms come with built-in support for RSS feeds. Why? It’s a great way for users to keep up to date on your new content. Instead of loading up a dozen favorite sites, they can look at one feed reader and then decide what to pursue further. So what if you don’t use a blogging platform or CMS that creates a feed for you? You can create one yourself in PHP. It’s pretty simple. [...]

  18. 55 Awesome PHP Tutorials for Noobs — ProgrammerFish - Everything that's programmed! said this on

    [...] 22)How to Create an RSS Feed for your Site in PHP This tutorial will show you how to create an RSS feed in a few simple steps. [...]

  19. 55 خودآموز PHP براي تازه كار ها « برنامه نويسي دلفي، سي شارپ ، ويژوال بيسيك ، دات نت said this on

    [...] 22)How to Create an RSS Feed for your Site in PHP This tutorial will show you how to create an RSS feed in a few simple steps. [...]

  20. Brendon Howes said this on

    Try & Preserve your iPad for No fee! -> http://bit.ly/cFBuis

  21. chip said this on

    How to Create an RSS Feed for Your Site in PHP for thanx.

  22. Boyd Tepperberg said this on

    Your site offers a lot of unique insights and information. I haven’t really thought about it like that.

  23. 55 خودآموز PHP براي تازه كار ها | برنامه نويسي از اهل زمين said this on

    [...] 22)How to Create an RSS Feed for your Site in PHP This tutorial will show you how to create an RSS feed in a few simple steps. [...]

  24. » Web Cash » Blog Archive » How to Create an RSS Feed for Your … said this on

    [...] Source: Bing: make cash rss feed [...]

  25. coach stores said this on

    I like it!

  26. polo outlet said this on

    Good!Very interesting, great creation.

  27. Roger Felicione said this on

    I simply entered a lengthy and thorough remark, and when I tried to distribute it my FireFox freaked out.

  28. Wilfredo Baldus said this on

    You truly Discount Coach Handbags& Free Shipping make it seem really easy together with your presentation however I obtain this particular subject to be actually some thing which I think I would never comprehend. It appears too complicated and very broad for me. I will be looking forward for your next post, I will attempt to receive the hang of it!

  29. North Face Sale said this on

    thank you to share!

  30. dogyWrag said this on

    похудеть на 5 10 кг бесплатные сайтымедсестра диетологдиета русланы писанки. не есть после 15-00диета для девочек за неделю збросить 5 кгпрочитать бесплатно онлайн книгу диета доктор борменталь9 дней диета молокодиета диффузные изменения в паренхиме почеккак похудеть на десять килограмовчай похудейкадиспепсия ребенок 2 месяца масса 4800 рассчитать диетуэффективная диета на которой можно скинуть 15 кг. за месяцдиета № 10 при инфаркте миокардакаким образом похудела хилари даффдиета для очень полныхдиетформула очищение от шлаков и токсиновможно ли на диете есть мюслиинеститут питание диеты похудениядиета из чечевицы и кефирасбалансированная диеты для похуденияголипедимическая диета стол № 4

  31. Billye Beranek said this on

    I have recently started a site, the information you offer on this site has helped me greatly. Thanks for all of your time & work.

  32. Lizabeth Cuneo said this on

    PHP fundamentally is a hypertext preprocessor and its a widely utilized scripting language that was designed to make it possible for dynamic webpages to work.

  33. North Face sale online said this on

    The North Face Better Than Naked Jacket is a seemingly weightless.

Leave a Reply