PHP Generating an RSS Feed
Listed In PHP and MySQL » Database Interaction — Viewing Full TutorialYou can use this handy technology to give information to your visitors on-the-fly without them even having to visit. This combs out all the things they might not want to see, and lets them choose what to read. For this tutorial you'll need something that updates every now and then, like a tutorial system, news system, a forum perhaps. They must also have an id field, a title field and I recommend a description field too, however you can simply echo out some of the text. Let's start off!
<?
// Config block for the script, edit where needed.
$sqltable = "news";
$sqlretrieve = "30";
$rsstitle = "My News Feed";
$rssdesc = "Fresh news from yoursite.com";
$rsslink = "http://www.yoursite.com";
header("Content-type: text/xml");
echo "<?xml version="1.0" encoding="UTF-8"?>"; // Declares this as an XML document, which is needed for RSS.
include("dbconfig.php"); // include your database config details or add them here.
// Let's echo this feed..
echo '<rss>'; // you can add the version attribute if you *really* want..
echo '<channel>
<title>'.$rsstitle.'</title> // the title of the feed
<description>'.$rssdesc.'</description> // small description
<link>'.$rsslink.'</link>'; // Echos the link to your website
$data = mysql_query("SELECT * FROM `$sqltable` LIMIT $sqlretrieve");
while($row = mysql_fetch_array($data)) {
echo '<item> // begins the item
<link>'.$rsslink.'</link> // direct link to the news
<title>'.$row['title'].'</title> // change title to whatever the title field is
<description>'.substr($row['content'],0,140).'</description> // a short extract (140 chars) from the full article</item>';
}
// We've just outputted all the news items (ie database results)
// Now to close the feed
echo '</channel></rss>';
?>And that's it! The code is commented as it goes along, so you can't possibly get lost!
