« Back to the blog

18

Mar

2009

77

Create an RSS feed with PHP

Create an RSS feed with PHP

Having an RSS feed on your website is a great way of sharing your content with the rest of the Internet. It’s not a new technology and it’s probably something that you use on a daily basis. If you have a blog or use any form of CMS, that software will most likely handle the creation of your RSS feed for you.

Sometimes, however, it might be necessary for you to create a RSS feed yourself. Perhaps you have just won a new client who’s current site has a old bespoke CMS which they like and want to keep, but you want to be able to publish their updated content via RSS. Hopefully this tutorial will help you to achieve this.

What is RSS?

RSS, in its current form, stands for Really Simple Syndication and is a family of web formats to publish frequently updated content. The RSS Feed (as it is commonly known) can then be read by the users feed reading software or by another website which wishes to ‘syndicate’ the content of that feed.


The RSS format is based on XML that is built using standardised tags. Here is an example of a basic RSS document, we will be generating something similar using PHP later in this tutorial:

<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
    <channel>
        <title>My RSS feed</title>
        <link>http://www.mywebsite.com/</link>
        <description>This is an example RSS feed</description>
        <language>en-us</language>
        <copyright>Copyright (C) 2009 mywebsite.com</copyright>
        <item>
            <title>My News Story 3</title>
            <description>This is example news item</description>
            <link>http://www.mywebsite.com/news3.html</link>
            <pubDate>Mon, 23 Feb 2009 09:27:16 +0000</pubDate>
        </item>
        <item>
            <title>My News Story 2</title>
            <description>This is example news item</description>
            <link>http://www.mywebsite.com/news2.html</link>
            <pubDate>Wed, 14 Jan 2009 12:00:00 +0000</pubDate>
        </item>
        <item>
            <title>My News Story 1</title>
            <description>This is example news item</description>
            <link>http://www.mywebsite.com/news1.html</link>
            <pubDate>Wed, 05 Jan 2009 15:57:20 +0000</pubDate>
        </item>
    </channel>
</rss>

Take a look at the RSS Wikipedia page for a full history of RSS and it’s various different versions.

Creating the feed

As we know, RSS is made up of standardised XML tags which you would normally find in a flat XML file. What we are going to do is create this standard XML data dynamically using PHP. This means that the URL for our feed will end with the .php extension, but we will tidy this up later in the tutorial.

So, lets start building the PHP script. The first thing we are going to do is tell PHP what type of data we would like to output (I am going to break each section of the script down, but I will include it in full at the end):

<?php
    header("Content-Type: application/rss+xml; charset=ISO-8859-1");

The header() function that we have called is telling PHP to output our data using the XML MIME type as well as to use the ISO-8859-1 character set. This makes sure that our content is delivered to the users in the correct format.

Now we are going to define our database connection details and create the header XML tags for our RSS feed. I’m going to statically assign the feed information tags just to keep it simple, however, you may wish to expand on this to dynamically set these. That way, you can re-use this code as a function or even go a step further and use it to build your own PHP class. The actual feed data will be kept in a variable called $rssfeed.

    DEFINE ('DB_USER', 'my_username');
    DEFINE ('DB_PASSWORD', 'my_password');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'my_database'); 

    $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
    $rssfeed .= '<rss version="2.0">';
    $rssfeed .= '<channel>';
    $rssfeed .= '<title>My RSS feed</title>';
    $rssfeed .= '<link>http://www.mywebsite.com</link>';
    $rssfeed .= '<description>This is an example RSS feed</description>';
    $rssfeed .= '<language>en-us</language>';
    $rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';

Next, we need to extract our data by looping through our MySQL database to create the <item> tags. I’m not going to explain this part in too much details as it’s not point of this tutorial and you may do this differently. We are going to assume that our MySQL table (“mytable”) has columns called title, description, link and date which hold the relevant data:

    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');

    $query = "SELECT * FROM mytable ORDER BY date DESC";
    $result = mysql_query($query) or die ("Could not execute query");

    while($row = mysql_fetch_array($result)) {
        extract($row);

        $rssfeed .= '<item>';
        $rssfeed .= '<title>' . $title . '</title>';
        $rssfeed .= '<description>' . $description . '</description>';
        $rssfeed .= '<link>' . $link . '</link>';
        $rssfeed .= '<pubDate>' . date("D, d M Y H:i:s O", strtotime($date)) . '</pubDate>';
        $rssfeed .= '</item>';
    }

    $rssfeed .= '</channel>';
    $rssfeed .= '</rss>';

    echo $rssfeed;
?>

The first part of this section connects to the MySQL database using the constants which we defined at the start of the script. Then we perform a basic SQL query to pull out all our data from the database in date order. The final part of the query, DESC, ensures that the newest content will appear first in the users RSS reader.

Next, we look at each row of data from the results of the query using a while loop. In each loop cycle, the first action performed is the extract() function to create a set of variables that take the name of the columns of the database, in my case $title, $description, $link, and $date. We then add the data contained in these variables to our main $rssfeed variable. When it reaches the final row of data, the while loop ends and we apply the closing XML tags.

The final step of the script is to actually output the data we have collected. This is simply done by echoing the $rssfeed variable. Here is the code in full:

<?php
    header("Content-Type: application/rss+xml; charset=ISO-8859-1");

    DEFINE ('DB_USER', 'my_username');
    DEFINE ('DB_PASSWORD', 'my_password');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'my_database'); 

    $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
    $rssfeed .= '<rss version="2.0">';
    $rssfeed .= '<channel>';
    $rssfeed .= '<title>My RSS feed</title>';
    $rssfeed .= '<link>http://www.mywebsite.com</link>';
    $rssfeed .= '<description>This is an example RSS feed</description>';
    $rssfeed .= '<language>en-us</language>';
    $rssfeed .= '<copyright>Copyright (C) 2009 mywebsite.com</copyright>';

    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');

    $query = "SELECT * FROM mytable ORDER BY date DESC";
    $result = mysql_query($query) or die ("Could not execute query");

    while($row = mysql_fetch_array($result)) {
        extract($row);

        $rssfeed .= '<item>';
        $rssfeed .= '<title>' . $title . '</title>';
        $rssfeed .= '<description>' . $description . '</description>';
        $rssfeed .= '<link>' . $link . '</link>';
        $rssfeed .= '<pubDate>' . date("D, d M Y H:i:s O", strtotime($date)) . '</pubDate>';
        $rssfeed .= '</item>';
    }

    $rssfeed .= '</channel>';
    $rssfeed .= '</rss>';

    echo $rssfeed;
?>

I mentioned earlier that I would tidy up the .php extension of the feed. I don’t know about you, but I find this a little bit ugly. When you see RSS feeds that have been generated by WordPress for example, you don’t see the actual file name, you just get the containing folder. To do this, create a folder in the root directory of the site and call it ‘feed’. Create a file in this new folder called ‘index.php’ and copy the code above into it. This leaves us with a nicer looking feed URL, in the case of this example, http://www.mydomain.com/feed/.

It really isn’t that necessary to tidy the feed URL, but I think it just looks a little neater.

Conclusion

Now that you have created your feed, you can link to it from your site or publish it using a service such as FeedBurner. But there is an extra step which will allow your visitor’s browsers to automatically detect the RSS feed on your site. In the <head> section of you pages, include the following tag (obviously changing the URL to your feed):

<link rel="alternate" href="/feed/" title="My RSS feed" type="application/rss+xml" />

Thanks for reading, it’s the first tutorial we have published and we hope it helps you out in some way. Please leave a comment below, we would love you hear what you have to say.

Resources

77 Responses to “Create an RSS feed with PHP”

Comments

  1. Gary Black Says:

    March 25th, 2009 at 8:50 am

    Great article
    With RSS becoming more and more popular over the years I have no doubt this will prove invaluable in the future.

    Thanks

  2. RSS Feeds for Error Messages Says:

    April 15th, 2009 at 1:48 pm

    I think it’s easier to create an RSS feed using the DOM model than writing it out like this, as I do in my example.

    It sounds intimidating, but I think you’ll find it is just as easy.

  3. Tim Wright Says:

    April 19th, 2009 at 8:28 pm

    any reason you chose the ISO charset over utf8?

    • Ian Harris Says:

      April 19th, 2009 at 10:34 pm

      Hi Tim,

      MySQL uses the Latin1 (ISO-8859-1) character set by default, so it seems to make sense to use this character set for my RSS feed as I am taking my information directly from a (default) MySQL database.

      However, you raise a good point because I believe that all of the ISO-8859-1 characters are included within the UTF-8 set, so using either character set would have been valid.

      Thanks for the comments Tim.

      Ian

      • Jacob Says:

        July 19th, 2011 at 5:29 pm

        Hi Ian,

        Great Stuff! its working fine in my project. but i could not understand why it shows only 6 feeds in my local host (wamp server).. i have added more than 20 feeds in my table.

        kindly advice me how to display all feeds…

        thanks a lot…

        regards,
        Jacob

  4. tkmk Says:

    May 18th, 2009 at 11:34 pm

    Hi Ian,

    You’re a legend! I was close to getting somebody in to code this for me but I decided to search online and stumbled across this article. It was spot on and the steps were detailed very well and were easy to follow.

    Thanks

  5. tkmk Says:

    May 19th, 2009 at 5:38 pm

    No problem. I have another question for you. Do you konw how I can remove the timestamp from the date? My DB doesn’t hold the time so the code shows a value of 00:00? Also I wanted to put “Posted on” in front of each date, but I’m struggling to find a solution to this too.

    Thanks

    • Ian Harris Says:

      May 19th, 2009 at 10:49 pm

      Hi again tkmk,

      Unfortunately, you cannot change the format of the date when you create the RSS feed. This is because the pubdate needs to be in the standard RSS format so that ALL feed readers understand it correctly.

      The modifications you are trying to achieve will need to be applied at the feed reader end, i.e. when your feed is being read/displayed. If this is what you are trying to do, take a look at Simple Pie. It’s a great tool to allow you to simply display RSS feeds with PHP.

      Hope this helps!

      Ian

  6. Mark Says:

    May 21st, 2009 at 1:30 pm

    I’m building a feed currently with the data from mysql.

    One issue is dealing with rogue characters, like a ’ curly apostrophe pasted from Word. I can’t control the database so I need to clean the data when I build the XML file. I could use CDATA but do you know of a function that will convert all these characters into accepted ones e.g. ’

    Regards

  7. Mark Says:

    May 22nd, 2009 at 7:57 am

    Thanks Ian – that link got me sorted.

  8. Mikael Says:

    May 24th, 2009 at 5:13 pm

    This is great, thanks a lot of the tutorial. I wasn’t able to make anything else work but this worked perfectly after a little fitting. Thanks. :-)

  9. polat alemdar Says:

    October 7th, 2009 at 9:11 am

    I got an error at line

    XML Parsing Error: not well-formed
    Location: http://mysite.com/podcast/rss.xml
    Line Number 10,
    Column 19:$rssfeed .= ”;
    ———————–^

    • Ian Harris Says:

      October 7th, 2009 at 1:32 pm

      Hi Polat,

      Try changing the file extension of your file to .php. If it has a .xml extension, the server will not parse the PHP code and you will end up with issues that you are seeing.

      Let me know how you get on,

      Thanks,

      Ian

  10. Scott Says:

    November 1st, 2009 at 6:24 am

    Wow! Thanks a lot Ian. Works great!

  11. youngbobby Says:

    December 14th, 2009 at 9:35 pm

    Hi, thanks for this great tutorial. I can’t believe how much i searched for this stuff especially the part where u taught about browser auto – detecting feed support using <link rel … . Thanks alot buddy. Kudos :-)

  12. shalini Says:

    December 18th, 2009 at 8:54 am

    Good Tutorial. Very easy to follow up.
    Thanks

  13. Kevin Mist Says:

    December 29th, 2009 at 2:07 pm

    Thanks so much for this article.. I have seen a few tuts on the subject before but you do an outstanding job describing the process. BTW.. I signed up for the RSS for this site :D

  14. Duane Charles Says:

    January 27th, 2010 at 8:13 pm

    Nice! Another great class from the prestigious WIU (WWW Internet University)

    Thanks…

  15. James Says:

    March 14th, 2010 at 8:50 am

    Thanks for sharing this script, this is exactly what I have been looking for. You have made it easy to understand. This makes managing rss feeds so simple. thanks again

  16. Leigh Says:

    April 11th, 2010 at 7:30 pm

    Brilliant tutorial, really easy and straigt forward to follow – I’ve just set up my first RSS!

  17. UD Says:

    April 14th, 2010 at 8:07 pm

    Hi man, i am getting an error in that part;
    $rssfeed = ”;

    because “?>” this closes to php tags i guess, how can fix this ?

    thanks

    • Ian Harris Says:

      April 14th, 2010 at 10:57 pm

      Hi,

      I’m sorry to hear that you are having a problem. Make sure that the XML header line is completely wrapped in single quotes and that there is no space before the ?>. Otherwise, this probably isn’t the cause of your problem.

      Let me know how you get on.

      Thanks,

      Ian

  18. rajesh Says:

    May 10th, 2010 at 5:58 am

    hi , i copied the above code and pasted in php file . but when i execute the file in the browser it is redirecting to yahoo site..http://add.my.yahoo.com/rss?url=http%3A%2F%2Flocalhost%2Ffeed%2Findex.php
    when i renamed the as then it is diplaying the output in XML form . i dont about xml can u please help me

    • Ian Harris Says:

      May 10th, 2010 at 8:07 am

      Hi Rajesh,

      It sounds like that is working correctly. Have a look to see what you default RSS reader is, it would imagine that it is set to Yahoo. When you execute the file, it will return the data in the RSS format and when your browser see this, it will try and open it in it’s default way.

      Thanks,

      Ian

  19. rajesh Says:

    May 12th, 2010 at 5:21 am

    Hi Ian,

    Thanks for your reply. i didnt understand one thing that is RSS case sensitive. why because i declared as RSS version=”2.0″ and declared some items i placed my code in server and when i clicks on “RSS” image then it is redirecting to yahoo and displaying the items list. if i give as rss version=”2.0″ then it is displaying the result as xml format.

  20. Jim Says:

    May 12th, 2010 at 11:03 pm

    Great guide Ian, the best I found and I’ve trawled a lot of sites.

    I’ve now created my first RSS but the pubDate is returning 01 January 1970, 01:00:00

    Any ideas how to fix it?

    (PS I’ll also be using your Replace broken images tip – thanks)

  21. sandeep Says:

    May 28th, 2010 at 5:07 am

    hello, very nice guidance, I have created my website’s feed using ur tutorial. It is working very fine.you can visit my website http://santech.cogia.net thanks a lot.

  22. Game Critic Says:

    May 31st, 2010 at 6:25 pm

    Thanks a lot for the tutorial, really appreciate it.

  23. Shah Khan Says:

    July 26th, 2010 at 12:36 pm

    i got this error:
    Warning: Cannot modify header information – headers already sent by (output started at /home/******/public_html/newest-rss.php:2) in /home/*/public_html/newest-rss.php on line 4

  24. Roy Says:

    August 9th, 2010 at 3:10 am

    Hi Ian,

    You made my day, and RSS simple. Your script is a great base to start with and it got me almost to the end. I started from scratch using your code as an example and it worked out great.

    I do would like to suggest people to use a RSS/Feed Validator to make their life easier, also adding a webMaster to the channel or even some images to item descriptions using CDATA is easy too.

    In any case, thanks for your perfect guide.
    Greetz, Roy

  25. Quick Says:

    September 5th, 2010 at 11:14 am

    Did nobody limit their results?

    $query = “SELECT * FROM my_table ORDER BY date DESC LIMIT 0,10″;

    This example limits to 10, or any amount wish to display at maximum, offset 0 is the start, 10 is the stop.

  26. Martin Says:

    September 16th, 2010 at 6:39 pm

    Why are people still using this oldschool way to create XML? Nowadays there are much better ways to create XML. PHP has excellent functionality for this like SimpleXML and DOMDocument.

  27. Gowri Says:

    September 25th, 2010 at 10:34 pm

    hello
    i followed your instruction and then i try to execute the code but i’m get this below error
    what should i do ?

    XML Parsing Error: not well-formed
    Location: http://localhost/gowri/rss/index.php
    Line Number 1, Column 3:<?
    –^

  28. Sofi Says:

    October 13th, 2010 at 11:18 am

    very good amd easy to follow. I was looking for at least an hour before i found yours. a tip for those none english characters. Use

  29. Darryl Walker Says:

    January 21st, 2011 at 9:25 am

    Your guide got me heading the right direction after I hit a bit of a wall trying this myself during the implementation of a larger system. Thanks!

  30. jem cook Says:

    January 26th, 2011 at 1:19 pm

    Hi, this looks great but I’m struggling somehow – I’ve set it all up as an index.php in a feed folder, pulling data from the database and I get a lovely ‘subscribe to this feed’ box at the top of the page, but none of the items list below – although they appear to be there in the source code – any idea what I may be doing wrong?

  31. Steve Bowyer Says:

    February 5th, 2011 at 2:03 am

    This is nice article , but you should code something like feed won’t be execute all mysql query everything you need to cache it or write an file.

    At least this works I will let you if I changed your codes regards.

  32. derrnbl Says:

    February 10th, 2011 at 9:28 pm

    So I take it that your feed gets created when you make a normal article or post on your website?

  33. sea breeze Says:

    March 29th, 2011 at 1:38 pm

    Thank you so much for this great information.

  34. Chaitanya Says:

    April 21st, 2011 at 6:17 am

    I have copied your code and changed the database connections and tables. When I try to open that page iam getting a download link of that php file. Please help me out from this

    • Suresh Says:

      April 28th, 2011 at 6:31 pm

      Even I face the same problem as Chaitanya. Please help us.
      And the feed I created will open in safari and IE7 but not in Firefox why it is so?

      • Ian Harris Says:

        May 1st, 2011 at 9:57 am

        @Suresh @Chaitanya I’m sorry to hear you are both having problems. It sounds like you have not specified the MIME type correctly at the top of the PHP file. Make sure that you have correctly added the header() function, this tells the browser that the content of the file is going to be in the RSS format.

        It also may be a problem with the encoding if you are using a language other than English. Try changing the encoded from ISO-8859-1 to something like UTF-8. You will need to change this both in the header() function and in the declaration.

        I hope this helps!

        • Ajay Says:

          February 1st, 2012 at 11:37 am

          I am aslo facing the browser issue. RSS is working in IE & Firefox but its not working in Chrome…In Chrome it displaying xml as it is….I have tried by changing characterset to UTF-8 but did’t worked…..Please help me out.

          thanks in advance….!

  35. Dan Says:

    May 17th, 2011 at 5:21 pm

    Quick and painless guide :)

    Thanks!

  36. Shaikh Asim Ahmed M. H. Says:

    June 10th, 2011 at 6:18 am

    Its a great toutorial specially for the begineers like me who are trying to discover new stuffs….

    Thanx a lot for the post…..

    May God Bless u guys…

    Regards
    Shaikh Asim Ahmed M. H.

  37. cywel Says:

    June 17th, 2011 at 2:58 am

    Great tutorial sir…

  38. Ashish Says:

    June 20th, 2011 at 11:28 am

    Neat and simple!! Thanks a lot! :)

  39. smith Says:

    June 29th, 2011 at 8:27 pm

    Hi i want to place the thumbnail in my site RSS Feed.can any body tell me how to place thumb in RSS.
    Thanks.

  40. manjula Says:

    July 23rd, 2011 at 8:22 pm

    good work. thanks lot

  41. lecole Says:

    July 26th, 2011 at 9:56 am

    Hi Ian,

    Your tutorial is great..I just some have question: I have my search engine on my site and i want the result would be generated based on my feed? is there anything to do

    Tnx.
    lecole

  42. Llewellyn Says:

    August 3rd, 2011 at 8:30 am

    Awesome Article helped alot

  43. harry Says:

    August 8th, 2011 at 8:57 am

    good explanation for RSS Nice one!!!!!!!

  44. James M. Says:

    August 14th, 2011 at 2:04 am

    Hi Ian this is a great post. I like how you demonstrate creating a feed from content in a database. Many classes and tutorials I have found provide functionality to build an RSS feed, but leave you in the dark when it comes to database integration.

    This tutorial uses a free Php class to generate Atom feeds as well as RSS:

    http://www.code-tips.com/2011/08/how-to-generate-feed-using-php-atom-10.html

    It uses the Php FeedWriter class ( http://phpfeedwriter.webmasterhub.net/ ) which works as an abstraction layer between the various formats. I haven’t used it much yet, but it seems good and is easy to use.

    Thanks

  45. Dorin Says:

    August 16th, 2011 at 9:17 am

    Works fine for entryes who doesn’t have html code.. however it’s any posibilities to echo the description by ignoring the html code?

  46. Peter Jarvis Says:

    September 8th, 2011 at 5:04 pm

    Hi there, great tut. Does anyone know how to add a hard return to the ends of the lines so that it formats properly. Thank you in advance.

  47. Amr Says:

    September 14th, 2011 at 8:00 am

    This is a great tutorial Ian. Thank you for sharing it with us. It was really helpful.

  48. Mrityunjaya Says:

    September 20th, 2011 at 12:06 pm

    This is really a great tutorial Thank you for sharing such a nice tutorial.

  49. Brent Says:

    September 25th, 2011 at 12:24 pm

    One problem… my feed is working but shows up as a giant paragraph. How can I get it spaced out nicely?

  50. Mohan Raja Says:

    December 12th, 2011 at 11:50 am

    simply superb…

  51. Aaron Wright Says:

    January 22nd, 2012 at 8:02 pm

    Nice tutorial. I normally use something like WordPress or Drupal to hack together a site. But for the site I just built, I had to do if from scratch. This tutorial should help me get the rss feed up and running to help me get more traffic. Many thanks!

  52. Victor Rodriguez Says:

    January 23rd, 2012 at 10:07 pm

    I need to understand one thing. This example of creation of an RSS feed on my website will automatically write information to my site?… or it wil feed other websites when I place information on my site? I am confuse. Please, help.

  53. Ajay Says:

    February 1st, 2012 at 9:41 am

    I have created feed folder and included index file with code mentioned in this post. What next should I do to generate feeds. Please help me as I am doing this for first time.
    thank you,

Trackbacks & Pingbacks

  1. abcphp.com
  2. Essential PHP Techniques for Web Designer and Developers | Desizn Tech
  3. Carron Media - Create an RSS feed with PHP
  4. Javacikiz : Bazı Bağlantılar
  5. Bazı Bağlantılar
  6. Adding a custom RSS feed to your website - Graphic Design | Website Design > UK Forums
  7. Bazı Bağlantılar « Seval Ünver
  8. Bazı Bağlantılar | Seval Ünver

Leave a Reply