How to Build an RSS Feed with PHP

1969 CamaroLast week, I decided to build a new website.  This isn’t the typical WordPress install that everyone seems to use anymore (whatever happened to programming?) and therefore, it didn’t have a built in RSS Feed.  This particular site is a picture site and I just planned on promoting my favorite car of all time.. the 1969 Camaro.  This being the case, I couldn’t just visit one of the many “create your own rss feed” sites and plugin my url.  There’s only one picture per page for this setup so those services simply won’t work.

The first thing I did was do a quick Google search.  I figured this would be easy to find and I’d just copy some code.  To my amazement, I simply didn’t find any good resources for this, so… time for some PHP programming.  I checked out the specs over at rssboard.org and then I began.  The script I made is about as easy as it gets and the idea is simple.  Since my RSS Feed would be a query of more than one table (as is usually the case when you’re dealing with images), I just needed to do a mysql join on the tables that held the image, the title and description, and then add a date and meet all the specs.

Start with the typical connection to the database:

<?php
$db_name = ‘your_db’; // name of the database
$db_user = ‘db_user’; // database user
$db_pass = ‘password’; // password to connect to the database
$db_host = ‘localhost’; // host the database resides on

$db = mysql_connect( $db_host, $db_user, $db_pass );
if ( ! $db ) {
print “Error connecting to database server: “.mysql_error();
exit;
}

mysql_select_db($db_name);
?>

Now it’s time for some rss header requirements:

<? header(‘Content-Type: application/rss+xml’); ?>
<rss version=”2.0″ xmlns:atom=”http://www.w3.org/2005/Atom”>

And now we build the channel. I needed my final rss feed to simply show a title, description, image and date. No coding yet. I’m still just following the specs as required:

<channel>
<atom:link href=”http://www.69camaropictures.com/feed/” rel=”self” type=”application/rss+xml” />
<title>69 Camaro Pictures</title>
<description>RSS Feed for 69 Camaro Pictures</description>
<link>http://69camaropictures.com/</link>

Now starts the coding. We’ve already connected to the database, so let’s join the tables and run our query. You’ll notice I’m just ordering by the last 15 in descending order. In this way, my rss feed always pulls the latest 15 results (the most an rss feed can pull) and there’s no need to build a loop! No need to make this hard. I’m also doing a WHERE clause to make sure there’s a title as I want a title and picture for every line item. Modify the query to your table structure and liking.

<?
$result = mysql_query(“SELECT image.imageid, image.image, image.title, image.mydate, allcategories.mycategory, allcategories.catid as catid FROM `image` LEFT JOIN `allcategories` ON `image`.`imagecatid` = `categories`.`id` WHERE title <> ” ORDER BY images.id DESC LIMIT 0 , 15″)
or die(mysql_error());

This next part is the WHILE loop. If you’re new to programming and just trying this out for the first time, you might skip the WHILE loop for now. It’s just using some php functions to clean up the contents of the exported data before it displays on the page. Get your feed working first. Then come back and clean it up. I’ll still include it, in case some need it.

while($row = mysql_fetch_array( $result )) {
$mytitle = strip_tags($row[‘title’]);
$mytitle = str_replace (‘&nbsp;’,”,$title);
$mytitle = stripslashes (str_replace (‘&quot;’,”,$mytitle));
$category = str_replace (‘ ‘,’-‘,$row[‘mycategory’]);
$mydate = $row[‘mydate’];
$mydate = date(“r”, strtotime($mydate));
?>

Okay.. we started the channel above. Now we have to create the actual line items within that channel:

<item>
<title><? echo htmlentities($mytitle); ?></title>
<description>

Did you catch what I did there? If you’re new to php, make sure you understand that you can stick php code anywhere within html (so long as the page has a .php extension) by simply inserting a beginning php tag and an ending tag such as this:
<? this is your php code ?>

Now comes the part that I struggled mightily with. Interestingly enough, the official specs show examples of how to embed video and other objects but never mention pictures. What the heck? Turns out that it’s a pretty sloppy solution so I suspect they left that out intentionally as there’s no clear way to make it happen. I just kept trying (and failing) until I eventually figured it out. This next section will grab a large image, trim it down to 150 x 140 (or whatever size you specify) and display it perfectly in your rss feed.

&lt;IMG width=”150″ height=”140″ border=”0″ src=”http://69camaropictures.com/pics/images/pic/<?=$row[‘image’]; ?>”
alt=”my image”/&gt;</description>

It looks like I forgot a tag or two above there and the browser rendered my html incorrectly, but that’s the actual code you need and the reason it provided a challenge to me.

The next line is how you build a link to your page. You already have the url to your picture page and if you pulled all the data you need from your database on your query above, simply substitute those values and build your url. This is my structure:

<guid isPermaLink=”true”>http://69camaropictures.com/categories/<? echo strtolower($mycategory); ?>,<?=$row[‘catid’]; ?>/picture-<?=$row[‘imageid’]; ?>/</guid>

Finish your item out and close the tags. I will mention that you do need to use the date code above (or your own variation) in my WHILE loop to convert the date, as the date element must be an RFC-822 date-time for a valid RSS feed. You’re likely not exporting that format from your mysql database.

<pubDate><?=$mydate; ?></pubDate>
</item>
<? } ?>
</channel>
</rss>

That’s it! You can validate the feed at w3.org to make sure there are no errors. After you get your feed built, go to feedburner.com (a Google service) and burn a new feed with their service. Now, you can use their tools for a subscription service and automatic emails to your subscribers when new content is released on your site.

The code looks even simpler when you pull the database connection information out and simply do a php include statement to connect to your database. Here’s the simplified version (using the include statement to connect). Enjoy!

<? header(‘Content-Type: application/rss+xml’); ?>
<? include ‘rssconfig.php’; ?>
<rss version=”2.0″ xmlns:atom=”http://www.w3.org/2005/Atom”>
<channel>
<atom:link href=”<?=$site_url?>/feed/” rel=”self” type=”application/rss+xml” />
<title><?=$rss_title ?></title>
<description><?=$rss_description ?></description>
<link><?=$site_url?>/</link>
<?
include ‘../include/myconfig.php’; //this line just connects to the database
$result = mysql_query(“SELECT image.title, image.description, image.id, image.mydate FROM `image` WHERE title <> ” ORDER BY image.id DESC LIMIT 0 , 15″)
or die(mysql_error());

while($row = mysql_fetch_array( $result )) {
$mydate = $row[‘mydate’];
$mydate = date(“r”, strtotime($mydate));
?>
<item>
<title><? echo htmlentities($mytitle); ?></title>
<description>
&lt;IMG width=”150″ height=”140″ border=”0″ src=”<?=$site_url?>/pics/images/pic/<?=$row[‘image’]; ?>”
alt=”rss image”/&gt;</description>
<guid isPermaLink=”true”><?=$site_url?>/categories/<? echo strtolower($title); ?>,<?=$row[‘id’]; ?>/picture-<?=$row[‘id’]; ?>/</guid>
<pubDate><?=$mydate; ?></pubDate>
</item>
<? } ?>
</channel>
</rss>

1 Comment

Submit a comment

CommentLuv badge

reverse phone lookupTattoo DesignsSEO
My New Amazon Script Is Close!
A new php script for sale is coming!
Sign up to get notified

..