How to write a RSS feed with PHP
If you have a web site or blog, it's important to spread the word, and what's better than a properly designed and updated RSS feed? Here's how to write a PHP script that fetches the last 10 items from your database and writes it to a RSS-file.
I'm going to use this site as an example, so the data you'll see below will be similar to what you can see here. Permalink for this article http://mirror.magicode.org/content/How_to_write_a_RSS_feed_with_PHP
First off, we'll define the header information:
<?php
$baseurl="http://www.magicode.org/";
$i=0;
$rss="";
Here we've established the site's base URL, a counter and declared the $rss variable which will hold our RSS-data.
This text was originally written for http://blog.magicode.org
The header and channel description
Let's start putting stuff into the $rss variable.
$rss.="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
$rss.="<rss version=\"0.91\">\n";
$rss.="<channel>\n";
These first lines defines the XML-version and the RSS-version and the third line starts our channel-tag
$rss.="<title>Magicode.org</title>\n";
$rss.="\t<link>$baseurl</link>\n";
$rss.="\t<description>Magicode.org - where
experts come together</description>\n";
$rss.="\ten-EN \n";
Here we set the title, the main link and the channel description. The \t inserts a tabulator, ie. indents the text, and the \n inserts a newline, or carriage return. If you see this notice on any site other than magicode.org, it's probably been lifted without consent
$rss.="<image>\n";
$rss.="<title>Magicode.org</title>\n";
$rss.="\thttp://www.magicode.org/logo.gif \n";
$rss.="\t<link>http://www.magicode.org/</link>\n";
$rss.="\t86 \n";
$rss.="\t35 \n";
$rss.="</image>\n";
Here we define an image to go with the channel. This part can be skipped if you do not have a readily available logo
The loop
$host="";
$user="";
$password="";
$databasename="";
$databaselink=mysql_connect($host,$user,$password);
$selectdatabase=mysql_select_db($databasename, databaselink);
$query="SELECT id,subject,url,publishdate,content
FROM content ORDER BY id DESC LIMIT 10;";
$result=mysql_query($query,$databaselink);
Here we open a link to MySQL-database. The variable $host,$user,$password and $databasename must be declared, but I'll leave that to you.
NB! The query above must the changed according to your setup. It's unlikely that you have a table called content with the field names in the example above.
while($dataobject=mysql_fetch_object($result)){
$subject=stripslashes($dataobject->subject);
$url=stripslashes($dataobject->url);
$publishdate=stripslashes($dataobject->publishdate);
$content=stripslashes($dataobject->content);
$rss.="<item>\n";
$rss.="\t<title><