6.8. Creating an RSS Feed from Database Content

Problem

You want to notify the world about updates on your web site with an RSS feed.

Three easy-to-use feed-parsing tools—Feed2JS, RSS-to-JavaScript, and CaRP—can reformat RSS feeds from other sites and display them on your site

Figure 6-5. Three easy-to-use feed-parsing tools—Feed2JS, RSS-to-JavaScript, and CaRP—can reformat RSS feeds from other sites and display them on your site

Solution

Use a PHP script to get your web site content from a SQL database, format the records as valid RSS feed entries, and save the complete feed file to your web server.

First, define a connection to your SQL database:

	$dbName = "mydatabase";
	$conn = mysql_connect("dbhost","dbuser", "dbpassword") or die("Couldn't Connect.");
	$db = mysql_select_db($dbName, $conn) or die("Couldn't select database.");

Then define a function to generate the RSS code for individual items:

	function createItem ($title, $description, $link, $pubdate) {
	 $item  = "  <item>\n";
	 $item .= "   <title>".$title."</title>\n";
	 $item .= "   <description>".$description."</description>\n";
 	 $item .= "   <link>http://yourwebsite.com/".$link."</link>\n";
	 $item .= "   <pubDate>".$pubdate."</pubDate>\n";
	 $item .= "   </item>\n";
	return $item;
	}

To save the feed file on your web server, define the full server path to the file in the variable $feedfile:

	$feedfile = "/full/path/to/rss.xml";

Warning

Your web server must have write privileges for the directory the feed file will be saved in.

Also, define a variable for a properly formatted last-modified timestamp ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.