How to Easily Make your own RSS feed using PHP + SQL

RSS Feed is an important part of a website/blog to attract and bring back users and make them permanent readers. Blogs like wordpress have built in rss reader, but if your website doesn’t have a rss system this tutorial is just the thing you need.В  As we know, RSS feeds usually using to transfer some news to readers. Today I will tell you how to create such feeds and fill it with information from database.

Step 1. PHP

Ok, here are all used PHP files:

index.php

This file will generate RSS feed

PHP
<?php

require_once('inc/db.inc.php');
require_once('inc/rss_factory.inc.php');

$sSiteUrl = 'http://localhost/dolphin7_rep_svn/demos/9/';
$sRssIcon = 'https://dev-school.net/logo-tuts.png';

$aStoriesRSS = array();

$sSQL = "SELECT * FROM `stories` ORDER BY `id` DESC";
$aStories = $GLOBALS['MySQL']->getAll($sSQL);
foreach ($aStories as $iID => $aStoryInfo) {
    $iStoryID = (int)$aStoryInfo['id'];

    $aStoriesRSS[$iID]['Guid'] = $iStoryID;
    $aStoriesRSS[$iID]['Title'] = $aStoryInfo['title'];
    $aStoriesRSS[$iID]['Link'] = $sSiteUrl . 'view.php?id=' . $iStoryID;
    $aStoriesRSS[$iID]['Desc'] = $aStoryInfo['description'];
    $aStoriesRSS[$iID]['DateTime'] = $aStoryInfo['when'];
}

$oRssFactory = new RssFactory();

header('Content-Type: text/xml; charset=utf-8');
echo $oRssFactory->GenRssByData($aStoriesRSS, 'Our stories', $sSiteUrl . 'index.php', $sRssIcon);

?>

view.php

We will draw post page using this page

PHP
<?php

require_once('inc/db.inc.php');

$iStoryID = (int)$_GET['id'];
if ($iStoryID > 0) {
    $aStoryInfo = $GLOBALS['MySQL']->getRow("SELECT * FROM `stories` WHERE `id`='{$iStoryID}'");

    $sStoryTitle = $aStoryInfo['title'];
    $sStoryDesc = $aStoryInfo['description'];

    echo <<<EOF
<h1>{$sStoryTitle}</h1>
<div>{$sStoryDesc}</div>
<hr />
<div><a href="index.php">Back to RSS</a></div>
EOF;
}

?>

inc/db.inc.php

This is our database class. No need to give full code of that file here (it big enough). It always available as a download package.

inc/rss_factory.inc.php

This is our RSS factory class. Universal class which transforming array with information (in necessary format) into RSS code.

PHP
<?php

class RssFactory {

    // constructor
	function RssFactory() {}

    // rss generator
	function GenRssByData($aRssData, $sTitle, $sMainLink, $sImage = '') {
        $sRSSLast = '';
        if (isset($aRssData[0]))
            $sRSSLast = $aRssData[0]['DateTime'];

        $sUnitRSSFeed = '';
		foreach ($aRssData as $iUnitID => $aUnitInfo) {
			$sUnitUrl = $aUnitInfo['Link'];
			$sUnitGuid = $aUnitInfo['Guid'];
			$sUnitTitle = $aUnitInfo['Title'];
            $sUnitDate = $aUnitInfo['DateTime'];
			$sUnitDesc = $aUnitInfo['Desc'];

            $sUnitRSSFeed .= "<item><title><![CDATA[{$sUnitTitle}]]></title><link><![CDATA[{$sUnitUrl}]]></link><guid><![CDATA[{$sUnitGuid}]]></guid><description><![CDATA[{$sUnitDesc}]]></description><pubDate>{$sUnitDate}</pubDate></item>";
		}

		$sRSSTitle = "{$sTitle} RSS";
		$sRSSImage = ($sImage != '') ? "<image><url>{$sImage}</url><title>{$sRSSTitle}</title><link>{$sMainLink}</link></image>" : '';
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"2.0\"><channel><title>{$sRSSTitle}</title><link>{$sMainLink}</link><description>{$sRSSTitle}</description><lastBuildDate>{$sRSSLast}</lastBuildDate>{$sRSSImage}{$sUnitRSSFeed}</channel></rss>";
	}
}

?>

Step 3. SQL

We will need to execute next SQL in our database. We will create table with demo stories which going to show in RSS

SQL
CREATE TABLE `stories` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `description` text NOT NULL,
  `when` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `stories` (`id`, `title`, `description`, `when`) VALUES
(1, 'First story', 'First story description here', '2010-06-01 00:00:00'),
(2, 'Second story', 'Second story description here', '2010-06-02 00:00:00'),
(3, 'Third story', 'Third story description here', '2010-06-03 00:00:00'),
(4, 'Fourth story', 'Fourth story description here', '2010-06-04 00:00:00'),
(5, 'Fifth story', 'Fifth story description here', '2010-06-05 00:00:00'),
(6, 'Sixth story', 'Sixth story description here', '2010-06-06 00:00:00'),
(7, 'Seventh story', 'Seventh story description here', '2010-06-07 00:00:00'),
(8, 'Eighth story', 'Eighth story description here', '2010-06-08 00:00:00'),
(9, 'Ninth story', 'Ninth story description here', '2010-06-09 00:00:00'),
(10, 'Tenth story', 'Tenth story description here', '2010-06-10 00:00:00');

Conclusion

Today I told you how to create own RSS feed. Hope all my code easy to understand and comfortable to use. You can use this material to create own scripts into your startups. Good luck!