Tuesday, February 18, 2014

How To generate RSS FEED USING PHP AND MYSQL


Basic structure of RSS feed.
<?xml version='1.0' encoding='UTF-8'?> 
<rss version='2.0'> 
<channel> 

<title>Website Title </title> 
<link>Website URL</link> 
<description>Website description</description> 
<language>en-us</language> 

<item> 
<title>Item/Article Title</title> 
<link>Item/Article URL </link> 
<description>Items/Article description </description> 
</item> 

</channel> 
</rss>

Sample Database Table.
CREATE TABLE site_data
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(250),
link VARCHAR(250),
description TEXT
);

rss.php
Code contains PHP and XML RSS basic structure tags. So your feed link http://domain.com/rss.php.
<?php
include('db.php');
$sql = "SELECT * FROM site_data ORDER BY id DESC LIMIT 20"; 
$query = mysql_query($sql) or die(mysql_error());

header("Content-type: text/xml"); 

echo "<?xml version='1.0' encoding='UTF-8'?> 
<rss version='2.0'>
<channel>
<title>9lessons | Programming Blog </title>
<link>http://9lessons.info</link>
<description>Programming Blog </description>
<language>en-us</language>"; 

while($row = mysql_fetch_array($query))
{
$title=$row['title']; 
$link=$row['link']; 
$description=$row['description']; 

echo "<item> 
<title>$title</title>
<link>$link</link>
<description>$description</description>
</item>"; 

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