Sign in or register

How to make a dynamic RSS feed in PHP

HTML, PHP

by nunof, 19:05 24-03-2008 (updated at 21:45 17-12-2008)

We introduce the RSS feed format and teach how to make a dynamic feed in PHP.

What's an RSS feed?

Wikipedia's entry on RSS tell us that:

RSS (Really Simple Syndication) is a family of web feed formats used to publish frequently updated content including, but not limited to, blog entries, news headlines, and podcasts.

So, it's a file format used to publish content. It's useful because people can easily subscribe to these feeds and receive updated content of their liking when and where they like, from various sources in an organized manner. For an example of a RSS feed you can view this site's feed: Broculos.net RSS feed.

The software used to view RSS feeds is called a RSS reader and can be web based or desktop based. XML is used to specify the RSS format.

A link to the RSS feed is usually found together with a feed icon. More on this later.

Example RSS file

The RSS format is quite simple. In this tutorial we will use the RSS 2.0 Specification. We'll only use a few tags. You should see the specification if you need or want more.

An RSS is composed of a channel and a collection of items. Be aware that there's a maximum number of items you can have in your RSS feed. For example, in version 0.91 of the RSS specification, there's a limite of 15 items. Readers may also impose their own limits.

Here is a very simple example of a RSS file.

<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
    <channel>
        <title>Example RSS feed</title>
        <description>Example of a RSS feed, part of a programming tutorial on making a feed in PHP.</description>
        <link>http://www.broculos.net</link>
        <copyright>Copyright (C) 2008 Broculos.net</copyright>
        <item>
            <title>Example 1</title>
            <description>This is the description of the first example.</description>
            <link>http://www.example.com/example1.html</link>
            <pubDate>Mon, 29 Dec 2008 22:10:00 -0600</pubDate>
        </item>
        <item>
            <title>Example 2</title>
            <description>This is the description of the second example.</description>
            <link>http://www.example.com/example2.html</link>
            <pubDate>Thu, 03 Jan 2008 14:27:15 -0600</pubDate>
        </item>
    </channel>
</rss>

How to make a dynamic RSS feed in PHP

As you can see from the example, it's a very simple file format. But you don't want to make a new RSS file by hand every time something changes in your site.

So, you have 2 options: making a script to produce the RSS file or making a script that is the RSS file. I prefer the later because it's more simple and the first solution requires that you call the script every time you want to update the RSS feed.

Let's make our dynamic always-updated RSS feed. We only need to output the correct tags with content. Because this is just a proof of concept, the data is defined in the file. In a real world example, the content would be loaded from a database.

<?php
 
    /**
* For demonstration purposes, the data is defined here.
* In a real scenario it should be loaded from a database.
*/
$channel = array("title" => "Example RSS feed", "description" => "Example of a RSS feed, part of a programming tutorial on making a feed in PHP.", "link" => "http://www.broculos.net", "copyright" => "Copyright (C) 2008 Broculos.net");   $items = array( array("title" => "Example 1", "description" => "This is the description of the first example.", "link" => "http://www.example.com/example1.html", "pubDate" => date("D, d M Y H:i:s O", mktime(22, 10, 0, 12, 29, 2008))) , array("title" => "Example 2", "description" => "This is the description of the second example.", "link" => "http://www.example.com/example2.html", "pubDate" => date("D, d M Y H:i:s O", mktime(14, 27, 15, 1, 3, 2008))) );   $output = '<?xml version="1.0" encoding="ISO-8859-1"?>'; $output .= '<rss version="2.0">'; $output .= "<channel>"; $output .= "<title>" . $channel["title"] . "</title>"; $output .= "<description>" . $channel["description"] . "</description>"; $output .= "<link>" . $channel["link"] . "</link>"; $output .= "<copyright>" . $channel["copyright"] . "</copyright>";   foreach ($items as $item) { $output .= "<item>"; $output .= "<title>" . $item["title"] . "</title>"; $output .= "<description>" . $item["description"] . "</description>"; $output .= "<link>" . $item["link"] . "</link>"; $output .= "<pubDate>" . $item["pubDate"] . "</pubDate>"; $output .= "</item>"; } $output .= "</channel>"; $output .= "</rss>";   header("Content-Type: application/rss+xml; charset=ISO-8859-1"); echo $output;   ?>

The second part of the script is the actual making of the RSS feed. It expects a $channel variable and an $items array with its respective values matched to the necessary keys.

After building the XML and storing it in the $output variable we need to display it. Before displaying the actual XML, we send an header indicating the content type of the file. In this case we say it's an RSS XML file. Finally, we output the result. You can see this example RSS feed working.

How to make browsers recognize your RSS feed

Now you should make your RSS feed available for everyone who wants to subscribe to it. Besides putting a link in your site for the RSS feed you should also take on additional step.

There's an HTML tag that you can use to indicate that you have an RSS feed. You should put it between the head tag.

<link rel="alternate" type="application/rss+xml" title="Title of the feed (RSS 2.0)" href="rss.php" />

You should specify the correct title of your RSS feed as well as its location.

For browsers that are RSS-enabled, this guarantees a simple way for your RSS feed to be detected. They usually indicate that a RSS as been detected by displaying a RSS icon in the location bar.

Conclusion

Don't forget - we only talked about the most basic tags. You should see the complete specification to know better what to include and what to leave out.

The code we produced is not very reusable. You could build a RSS writer with a few classes or turn it into a function.

What more there's left to do? You should use the standard RSS icon, make sure the RSS is valid by validating your RSS feed and for more advanced features for your RSS feed like visitor stats you could use FeedBurner.

Resources

Comments

19:27 09-04-2008sfradette

Dont forget to escape guillemets on the line 23 and 24 otherwise it wont work

10:06 11-04-2008nunof

Thanks for the heads up. It was actually a problem in copy-pasting the code.

I changed the outer quotes to single quotes.

17:28 23-04-2008josemota

Nice tutorial indeed. I just want to emphasize the big point of the tutorial: you are actually generating XML the same way you generate HTML. You can also set the URL to a php file instead of a regular XML as long as you say the MIME type is application/rss+xml. Dynamic generated content at its maximum power!

23:21 08-05-2008Fabio

animaisos.org/rss

23:23 08-05-2008Fabio

Nao estou conseguindo fazer funcionar no animaisos.org/rss. O codigo esta correto mas nao aparece nada de rss. Aguardo resposta. obrigado

00:13 09-05-2008Fabio

Consegui, obrigado!

09:55 09-05-2008nunof

Fico contente que tenhas conseguido!

06:27 21-09-2008Keith

Very nice article, Appreciate it! Thumps up for you

08:04 04-02-2009tedivm

I would highly suggest using something like SimpleXML over manually generating your XML. In the long run you are very likely to run into parsing errors or other issues otherwise.

06:29 05-03-2009gaurav

Hello,
im found following error when i check this from FEED Validator site.

XML parsing error: :1:0: no element found

Feeds should not be served with the "text/html" media type

my url is : http://chitkara.edu.in/dnn/rss_site.php

00:18 09-04-2009Charles

obrigado! funcionou perfeito no site q estou fazendo!

23:48 24-10-2009matsolof

I did'nt realise I had to convert special characters to HTML entities. In other words, disregard the code right above (hopefully, it will be removed).
This revised version of the code will automagically exclude older items. It uses a data base of php files. Make the necessary changes (the name of the site etc.) and save this as "rss.php":
<?php
$output = '<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="http://www.mySite.com/myRss.xml" rel="self" type="application/rss+xml" />
<title>My RSS Channel</title>
<link>http://www.mySite.com/index.php</link>
<description>My description</description>
<language>en</language>'."\r\n\r\n";
foreach(glob('rss/*') as $value){
require $value;
$today = date('Y-m-d');
$diff = (strtotime($today) - strtotime($pub_date)) / 86400; //86400 sek == 24 hours
if($diff > 100){$output .= '';} //remove items older than 100 days
else {$output .= '<item>
<title>'.$title.'</title>
<pubDate>'.$pubDate.' 00:00:00 GMT</pubDate>
<category>'.$category.'</category>
<link>http://www.mySite.com/'.$link.'</link>
<guid isPermaLink="true">http://www.mySite.com/'.$link.'</guid>
<description><![CDATA['.$description.']]></description>
</item>'."\r\n\r\n";}}
$output .= '</channel>
</rss>';
header("Content-Type: application/rss+xml; charset=utf-8");
echo $output;
?>
In the same directory as "rss.php", a) make a directory named "rss" and b) save this as "1000.php" in the directory named "rss":
<?php
$pub_date = '2009-10-24';
$title = 'My title';
$pubDate = '24 Oct 2009';
$category = 'My category';
$link = 'my_link.php';
$description = '<p>My description.</p>';
?>
Add more files in the directory "rss". Name them "0999.php", "0998.php", etc. (to get the earliest items at the top of the rss file). If you write a lot of rss, you may want to start with "10000.php" or perhaps even "100000.php".
Good luck!

23:53 24-10-2009matsolof

PS: If you need to convert special characters to HTML entities and other similar tasks, you may find my Automagic code generator helpful.

23:59 24-10-2009matsolof

The code generator can be found at:
http://www.mkforlag.com/english/tools/code_generator/

13:42 25-10-2009nunof

Thank you, that's very useful.

03:53 29-12-2009alexandre

mto obrigado!!
funcionou perfeitamente no meu site,
agradeço oo post!

Leave a comment

RSS article feed RSS article feed

© 2007-2010 Coconuts. Contact us.