RSS is a format for publishing frequently changing content like news, a list of blog posts or directories. Using RSS readers like Google Reader or Apple Mail, you can read all your daily information at one place, offering a much better overview and faster processing than visiting every single website.
An RSS feed from the technical point of view is nothing more than a specially formatted XML document. It contains a general feed description as well as a headline, a link to the source and the content or an excerpt for every item. In this arcticle, I will show you how to create your own feed using PHP.
First of all, we set up the header information to specify that it is an XML document.
<?
header("Content-Type: text/xml; charset=utf-8");
print "<?xml version=\"1.0\" ?>\n";
?>
Then we add general feed information like the feed’s name, its description and the source URL.
<rss version="2.0"> <channel> <title>Feed's title</title> <description>My site's cool feed</description> <link>http://www.my-site.com</link>
Now the real work begins. We need to get the necessary information for every item to be published. This could mean simply selecting information from a database, but also parsing XML or HTML files and gathering the information we need. It all depends on the datasource. When looping over every single item of our information, I assume we fill the variables $item, $content and $link, containing what the name suggests. We print the following block for every step of the loop.
<item> <title><?= $title ?></title> <description><?= $content ?></description> <link><?= $link ?></link> </item>
Finally, we close the opened tags.
</channel> </rss>
That’s pretty much all you need to set up your own feed. But there are some pitfalls I discovered when creating my first feed. Because we’re working with XML documents, we have to convert special characters like < and > to < and >. This can be archieved by using PHP’s htmlspecialchars funtion. However, I had to use it twice for a proper display in Google Reader. I would have expected Google to escape the content properly, but looks like they just pass the output to the frontend.
Now I wish you a lot of fun creating your own feed. If you need some information on how to parse HTML files with PHP and create an RSS feed from almost any website, just leave a comment and I will provide some examples.
[...] [...]