« Back to the blog

18

Mar

2009

40

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

40 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

  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

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

Leave a Reply