Creating an RSS Feed with PHP

It’s fairly straightforward to use PHP to create an RSS feed from your existing database. In this example, we take a database table containing new items, retrieve the last 15 in order and then output in RSS2.0 XML format. This chiefly consists of a title description and link for the channel (your site) and the same for each item (seperated using <item> and </item> tags). The first line (which must be the first line) is very important — it declares the data below to be XML, and it will not be correctly recognized if this line isn’t present.

Place the PHP file in, for example, a subdirectory called /feed/ and call it index.php. When you add it to a news aggregator or submit it to a feed tracker, the URL will be http://www.yoursite.tld/feed/

<?php echo "<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Title</title>
<description>Description of site</description>
<link>http://www.yoursite.tld</link&gt;

";

require('databaseconnector.php');

$result = mysql_query("SELECT * FROM table ORDER BY date DESC LIMIT 15",$db);

if($row = mysql_fetch_array($result)) {
do {

echo "
<item>
<title>$row[0]</title>
<description>$row[1]</description>
<link>http://www.yoursite.tld/script.php?date=$row%5B0%5D</link&gt;
</item>
";

} while ($newsrow = mysql_fetch_array($result));
} else {
echo "No newsitems found.";
}

echo "
</channel>
</rss>
";

?>

Once you have the script generating the feed you want, you can add it to your site by inserting the following in your <head> section:

<link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.yoursite.tld/feed/&quot; />

Advertisements
This entry was posted in Computing. Bookmark the permalink.