dizzysoft

web development for search engine optimization

A SimpleXML RSS Feed

I love playing with RSS feeds. One of the easiest ways to do this is using PHP’s SimpleXML. Here’s how you create an XML feed with this easy-to-use library


<?php
/*
Get info from your MySQL DB. This, of course, will differ based on your DB.
*/
mysql_select_db($database);
$query = "SELECT id, headline, date FROM content ORDER BY date DESC LIMIT 10";
$rss_query= mysql_query($query);

$rss_seed= <<<XML
<?xml version='1.0' standalone='yes'?>
<rss version="2.0">
</rss>
XML;

$rss= new SimpleXMLElement($rss_seed);
$channel= $rss->addChild('channel');
$channel->addChild('title',"Write your own title");
$channel->addChild('description', "Give a little description of what is in your feed");
// This is the permalink to your rss feed. It is required. For instance, if you put this file as index.php in your /rss/ directory, you could call it as:
$channel->addChild('link', "http://www.yourwebsite.com/rss/");

while($row= mysql_fetch_assoc($rss_query)) {
$item= $channel->addChild('item');
// technically you only need either a title or a description as an item.
$item->addChild('title', $row[headline]);
// if you know the URL for the item, put it here. This is optional.
$item->addChild('link', "http://www.yourwebsite.com/item/$row[id]");
// technically this is optional, but highly recommended
$item->addChild('guid', $row[id]);
}

mysql_free_result($rss_query);

$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($rss->asXML());
echo $dom->saveXML();
?>

To learn a little more about the specifications for an RSS feed, Harvard has the specs.

For troubleshooting an RSS feed I’ve created, I find an RSS validator to be priceless.

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Examples

Recent Comments

Topics