Create an RSS feed with PHP

Originally posted on 18th March 2009 by Ian Harris

« Back to articles

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 an 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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):

1
2
<?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.

1
2
3
4
5
6
7
8
9
10
11
12
13
    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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    $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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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):

1
<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

Comments

Comments are closed.