Creating A Custom RSS Feed With PHP
By jacharless
So, you built a website with an amazing strength of potential for millions of internet aficionados to venture, read information, blog, whatever --and maybe make you a few pesos in the big scheme of things. There is a simple, yet powerful tool to gain traffic through: RSS. RSS means Really Simple Syndication. To syndicate just means gather all the info in once place, where people can subscribe, via their web browser, to an article list. But, the words "really simple" on the programming side, are not so simple --as you might have guessed. Creating an RSS Feed, should be quite easy. And after racking my brain for days over the programming connection between my existing PHP website and testing out several Feed Generators (( like Mag Pie or Simply Smarty )) had a moment where my iMac nearly plunged out the window. Luckily, I remained calm and went back to my old school PHP programming know-how for the answer to Customizing An RSS Feed without bloated parses.
Creating the entire Custom RSS Feed will take you minutes, literally. From here you can jack into Feedburner, Pheedo or any other Syndication you prefer. You will need 3 items in all.
• The Make File function
• The PHP-XML Hybrid File ( template )
• The Output Script
The customization of this type of Feed creates a username based RSS Channel in PHP, that returns valid. For each user generated page, you can place the link to that specific group of Articles on the website. The system automatically creates the RSS files needed. This means less work for you, more flexibility, certainly no manual entry - and if all goes well, increased subscribers.
Here's How To Make Your RSS Feed :
1. On the User Confirm page, you will need to call a MAKE FILE function. This tells the server to create a file titled USERNAME.RSS.PHP. The link or address [ http://mywebsite.com/feeds/username.rss.php] is what you will send to the various syndicates you prefer to use. It is vital you make this file, else the RSS Output will not be created.
• First, we get the post data when the user registers
• Create the name of the RSS file to be Username.rss.php.
Make File When User Joins
<?php
$USERNAME=$_POST ['USERNAME'];
$FILE = $USERNAME . '.rss.php';
if (!$handle = fopen($FILE, 'a')) {
echo "whoops! cannot open file ($FILE)";
exit;
}
$header = file_get_contents("users/rss.php");
?>The above function gets the Username and tells the server to MAKE FILE called USERNAME.RSS.PHP. Now, here is the tricky part: you will need to GET the basic RSS-PHP Template from the Main PHP-RSS File in the directory. why? This saves a lot of time and headache for you. All the function does is gets all the Template information and append it to the new file called Username.rss.php. This will include all the RSS Elements for each user who joins. Write the header to the new RSS file and move it to the proper directory. [ You may choose whatever folder you like, just so long as you remember where you created it so you may link it later on ]. The above code now automatically creates the RSS/PHP file in the directory. Now, in order for that file to be created, you need the base code or RSS Template and a connection to the database.
To connect to the database, create a file called: mydataconnect.php. Place it in each folder where there are data actions that are going to happen. Note: you do not want to add the database code to the RSS File itself, just in case it can be read by someone and an unwanted injection made into the database. I recommend giving the database connection file a unique name.
Database Connectivity
<?php $dbhost= 'HOST SERVER CODE'; $dbuser= 'USERNAME'; $dbpass= 'PASSWORD'; $conn= mysql_connect($dbhost, $dbuser, $dbpass) or die (); $dbname= 'NAME OF THE DATABASE'; mysql_select_db($dbname); ?>
Simple, right? Now, lets create the main RSS/PHP.
One of the unique features of RSS, it is written in XML, so you can customize the items, like the Title, URL, Photo of the main feed and then the Child Elements also. Some browsers will enable photos for each feed listing, some do not. Feedburner and Pheedo definitely do, by creating an XHTML (XML+HTM) page for the feed. This is great for putting Ads into feeds.
The issue with RSS/XML and PHP is the language. Communication between the two is like speaking Russian to a Dolphin, neither understand a word the other is saying. But, there is a way to unite the languages and everyone go home happy. This is called parsing. One language meets another and information is translated. In fact, the parser IS the translator.
To make the RSS/PHP work, we tell the output that this PHP File, should be read as an XML file. This is found in the Content Type. Most web pages tell you in the header what type of content is designed or allowed for the page. If you are using XHTML Transitional or even Strict, you can display pretty much any code. With PHP you need to specifically assign which Type it is. In this case, XML/RSS. Let's create the Main RSS Template file first and customize it for your users.
The PHP RSS Hybrid Template
<?php
header(Content-Type: application/rss+xml;
charset=ISO-8859-1);
require_once('mydataconnect.php');
$USERNAME= basename($_SERVER['SCRIPT_FILENAME']);
$USERNAME= str_replace('_',' ',$USERNAME);
$USERNAME= str_replace('.rss.php','',$USERNAME);
$USERNAME= ucfirst($USERNAME);
$feed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$feed .= '<rss version="2.0">';
$feed .= '<channel>';
$feed .= '<title>Your RSS</title>';
$feed .= '<link>http://www.yourwebsite.com</link>';
$feed .= '<description>Describe Website</description>';
$feed .= '<language>en-us</language>';
$feed .= '<copyright>yourwebsite.com</copyright>';
$query="SELECT * FROM RSS WHERE USERNAME='$USERNAME'
ORDER BY PUBLISHED DESC LIMIT 15";
$result = mysql_query($query) or die
();
while($row = mysql_fetch_array($result))
{ extract($row);
$LINK ="http://yourwebsite.com/TITLE.php";
$PHOTO ="http://yourwebsite.com/PHOTO1";
$feed .= '<item>';
$feed .='<image>';
$feed .='<url>$PHOTO</url>';
$feed .='<title>YOUR RSS</title>';
$feed .='<link>../$USERNAME.rss.php</link>';
$feed .='<width>50px</width>';
$feed .='<height>50px</height>';
$feed .='</image>';
$feed .= '<title>$TITLE</title>';
$feed .= '<description>$DESCRI</description>';
$feed .= '<link>$LINK</link>';
$feed .= '</item>';
}
$feed .= '</channel>';
echo $feed;
?>Explaining The Process
The Content Type Header MUST be on top and sent before any data can be translated by the server for the XML/PHP.
Now, we customize the Title of THIS File, removing the extensions, leaving just the username. So, if the file was named mrjones.rss.php, it will now be just mrjones. Why? Simple, "one query to bind them all" instead of doing multiple queries, bringing back all the information of that user only. Yes, you can customize it many ways, for specific categories in your database like
Home Improvement or Knick Knacks, so long as THIS MAIN FILE is named accordingly.
Now, with just the username, we mesh the PHP with the XML languages to create the display. Simply said, all we are doing is echoing the PHP like always. The beauty of it: when it is outputted, only the xml will be visible.
• Create the link to the Article.
• Get the location of the Photo to display.
• Build the RSS output ( .feed elements ).
Notice the main link is to the Custom RSS Feed, not the main website or main RSS Template. Again, this is the Main Template. Save THIS file as rss.php. This will be used when the user registers, to automatically create the customized username.rss.php for each one. From the code earlier, you saw how it automatically copies the new file into the users folder. The last bit of code goes into the user generated pages, so visitors can click and subscribe to that feed syndication. It is the Link to the username.rss.php
Link The RSS Per Title or Username
<?php
$result= mysql_query
("SELECT * FROM `ARTICLES` WHERE TITLE = '$TITLE'")
or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{ $USERNAME = $row['USERNAME']; }
echo "<a href="http://.../rss/$USERNAME.rss.php">
?>This last bit of code goes into your PHP Pages. It simply calls the Username from the Title of The Article and extracts that username. The Username then is queried in the RSS Table. Out pops the entire Feed for THAT USER.
Voila! A Valid RSS/PHP Feed. You may now add this to whichever feed syndication you prefer. It saves a lot of time and headache, doesn't require a lot of serverside code, files or includes. Sure you can use the includes for specific tasks and filters if you want.
Happy Feeding!
Comments
Its been a long time since I've written any script! You've laid this out nice and easy. Now, I have to go back to my C basics and rehone my skills... Voted up!




jacharless 10 months ago
Thank You Beth!