Creating an RSS News Feed with PHP and MySQL
Website Automation with PHP and MySQL, Part 16
Low End Mac Reader Specials
Memory To Go Special: New 2008 iMac 2GB $42 / iMac Intel Core2 DUO & MacBook Pro 2GB $36 - 1GB $20. MacPro 8 Core Memory 8GB kit $286 / 4GB kit $143 / 2GB kit $93 -- Free shipping available. LIfetime warranty.
Download Typestyler, still the Ultimate Styling Tool for Internet, Print and Video Graphics. Works great in Classic with a Native OS X Version on the way. Free Tryout: www.typestyler.com
LA Computer Company: Specials on AppleCare, iMac's, Apple Batteries and Apple A/C Adapters. Also Great prices on Used Apple Computers. Call 1-800-941-7654 Click Here.
OWC: NewerTech NuPower Batteries for iBook and PowerBooks Designed+Built in USA to run longer, LAST LONGER TOO! Free Battery Recycling Return Label; Quality High-Capacity from $99.95
Mac users can finally play Party Poker for Mac. Not only that, they can also learn how to play PokerStars for Mac.
Laptop Hardware Provided by TechRestore - Overnight Mac & iPod Repairs.
Compare products like desktop computers, laptops, and LCD TVs side by side! All the information and reviews to make the best purchasing decision for a new cell phone GPS products or MP3 players. The Ciao network makes searching products easy for you.
Dan Knight - 2003.02.27
It's been a long time since I've added any automation to the site, although I have made a few tweaks to existing automation, but this week we added one more significant piece to our ongoing site automation project, an automatically generated RSS news feed.
What's RSS?
An RSS (Rich Site Summary) news feed is a text file that others can use to find out what's new on your website. There's a standard format for these documents, which includes things like the domain name and URL, email for the webmaster, when the latest update took place, along with article titles, their URL, and usually a brief description or teaser.
There's a good introduction to them in Using RSS News Feeds.
I've been generating RSS news feeds for Low End Mac for a long time. Quite frankly, it's a tedious business. I've been slacking off on doing them because of the time involved. What time I have, I'd rather spend writing, editing, designing, trying to keep on on email.
And after about an hour or so of coding and debugging, I don't have to manually create an RSS feed any longer. PHP uses the same MySQL database that already tracks site content to generate a news feed.
Here's a snippet of the last one I created manually:
<?xml version="1.0"?> <!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.91.dtd"> <rss version="0.91"> <channel> <copyright>Copyright 1997-2004 Cobweb Publishing Inc</copyright> <pubDate>Fri, 14 Feb 2003 14:00:00 EDT</pubDate> <description>Resources for Mac users.</description> <link>http://lowendmac.com/</link> <title>Low End Mac</title> <image> <link>http://lowendmac.com/</link> <title>Low End Mac</title> <url>http://lowendmac.com/88x31.gif</url> <height>31</height> <width>88</width> </image> <webMaster>webmaster@lowendmac.com (Dan Knight)</webMaster> <managingEditor>webmaster@lowendmac.com (Dan Knight)</managingEditor> <language>en-us</language> <skipHours> <hour>1</hour> <hour>24</hour> </skipHours> <skipDays> <day>Saturday</day> <day>Sunday</day> </skipDays> <item> <title>Windows, Macs, OS X, and Real World Performance, Adam Robert Guha, Apple Archive</title> <link>http://lowendmac.com/archive/03/0214.html</link> <description>As Mac OS X improves and hardware gets faster, complaints of sluggishness will become nothing but a memory.</description> </item> <item> <title>Safari Update, Mac OS X 10.2.4, a Neat Haxie, and How Mail Can Better Fight Spam, Dan Knight, 10 Forward</title> <link>http://lowendmac.com/10/03/0214.html</link> <description>Safari mostly improved but adds a glitch, 10.2.4 seems just fine, a better CPU monitor, and ways Apple can leverage Mail to better fight spam.</description> </item> </channel> </rss>
The header only has one tricky part - the date. Everything else up there remains the same. The items change each day that we add new content. The tags pretty much explain the parts, which is a very nice feature of an RSS news feed.
The Program
I'm not going to give you the whole program. Program code will be set in monospace type and comments will be in regular type.
<?php
$db_server = "yourserver.com";
$db_username = "userID";
$db_password = "password";
$db_name = "mydata";
$connection = @mysql_connect($db_server,$db_username,$db_password);
mysql_select_db($db_name,$connection);
$filepointer = fopen("/usr/local/apache/sites/mydomain.com/htdocs/rss.txt", "w");
This was one of the tricky parts. Since the RSS newsfeed file, rss.txt, is in the root directory, I had to find out from our system administrator just how to write the file to the correct spot. During testing, I wrote it to the same directory I was writing the script in. (The \r indicates a return.)
We also had to have things set up on the server so we had permission to write the file. Without that, none of this works.
fputs ($filepointer, "<?xml version='1.0'?>\r<!DOCTYPE rss SYSTEM 'http://my.netscape.com/publish/formats/rss-0.91.dtd'>\r<rss version='0.91'>\r <channel>\r <copyright>Copyright 1997-2004 Cobweb Publishing Inc</copyright> \r <pubDate>");
The above line starts writing the text file with our news feed. This part only changes once a year as we update the copyright notice.
The next chunk of code is used to post the correct date and time in our file:
$rightnow = date(U);
$latestdate = mysql_fetch_array(mysql_query("SELECT * FROM links
WHERE timestamp <= $rightnow ORDER BY timestamp DESC LIMIT 1"));
fputs ($filepointer, date("D, d M Y h:i:s T", $latestdate[timestamp]));
The first line checks the current time and compares this with the latest timestamp in our MySQL database that's earlier than now. (We do this to assure that content scheduled for later release doesn't get posted in the news feed early.)
We then post the day, date, time, and time zone as the publication date. This will always match the moment when the most recent article went live.
- UPDATE: The format we originally presented was incorrect and included am/pm between the time and time zone - h:i:s a T - which produces an invalid RSS feed. Please use <http://feeds.archive.org/validator/> to validate your feed before sharing it with the world.
Next we close the publication date, describe the site, provide the base URL for Low End Mac as well as the site's name, and provide the URL and dimensions for a site graphic.
fputs ($filepointer, "</pubDate>\r <description>Resources for Mac users. </description>\r <link>http://lowendmac.com/</link>\r <title>Low End Mac </title>\r<image>\r <link>http://lowendmac.com/</link>\r <title>Low End Mac</title>\r <url>http://lowendmac.com/88x31.gif</url>\r <height>31 </height>\r <width>88</width>\r</image>\r
Here we provide the email address for the webmaster and managing editor, which in our case is the same person. Someone having a problem with the news feed could use this to contact us and let us know about the problem.
<webMaster>webmaster@lowendmac.com (Dan Knight)</webMaster>\r <managingEditor>webmaster@lowendmac.com (Dan Knight)</managingEditor>\r
Low End Mac is published in English, and most of our writers use US English. So we cover that next.
<language>en-us</language>\r
We can tell what hours and days the site isn't updated, which is done in GMT. For those outside the UK, this can involve some head scratching. Basically we don't publish new articles between 9:00 p.m. and 6:00 a.m. (We try to have our publishing day done by noon Eastern Time to make time for lunch, email, and my other job.)
<skipHours>\r <hour>1</hour>\r <hour>2</hour>\r <hour>3</hour>\r <hour>4</hour>\r <hour>5</hour>\r <hour>6</hour>\r <hour>7</hour>\r <hour>8</hour>\r <hour>23</hour>\r <hour>24</hour>\r </skipHours>\r <skipDays>\r <day>Saturday</day>\r <day>Sunday</day>\r </skipDays>\r");
The Meat
That's all header. Except for the time stamp, it doesn't change. From here on, we're creating content based on information in our MySQL database.
First up, get today's articles, starting with the most recently published:
$get_links = mysql_query("SELECT * FROM links
WHERE pubdate = '$latestdate[pubdate]' and timestamp <= $rightnow
ORDER BY rank DESC");
while ($array = mysql_fetch_array($get_links))
{
fputs ($filepointer, "<item>\r<title>$array[linktext]");
if ($array[author]<>"")
{fputs ($filepointer, ", $array[author]");}
if ($array[columnname]<>"")
{fputs ($filepointer, ", $array[columnname]");}
fputs ($filepointer, "</title>\r<link>http://lowendmac.com
$array[path]$array[html]</link>\r<description>$array[description]
</description>\r</item>\r\r");
}
This is pretty similar to the code we use to display pages throughout the site. Instead of using just the title of the article as a link, we also include the name of the author and the column name as part of the title.
// This Date in LEM History
$thisdate = date(md);
$thisrecord = date(nd);
$today = date("F j");
$get_links = mysql_fetch_array(mysql_query("SELECT * FROM lemhistory
WHERE datefield = '$thisrecord'"));
if ($get_links <> "")
{fputs ($filepointer, "<item>\r<title>$today in LEM history</title>
\r<link>http://lowendmac.com/arc/$thisdate.html</link>\r<description>
$get_links[stories]</description>\r</item>\r\r");}
Following the new articles, we check our database to see if we have an archive covering this date in Mac and LEM History. Most days we do, but about once a month there's a date we still haven't posted new content on. Except for holidays, most of those will disappear as we add content almost every weekday.
// Previous Day's Links
$previous_date = mysql_fetch_array(mysql_query("SELECT * FROM links
WHERE pubdate < '$latestdate[pubdate]' ORDER BY timestamp DESC LIMIT 1"));
$previous_links = mysql_query("SELECT * FROM links
WHERE pubdate = '$previous_date[pubdate]' ORDER BY clicks DESC");
while ($previous_array = mysql_fetch_array($previous_links))
{
fputs ($filepointer, "<item>\r<title>$previous_array[linktext]");
if ($previous_array[author]<>"")
{fputs ($filepointer, ", $previous_array[author]");}
if ($previous_array[columnname]<>"")
{fputs ($filepointer, ", $previous_array[columnname]");}
fputs ($filepointer, "</title>\r<link>http://lowendmac.com
$previous_array[path]$previous_array[html]</link>\r<description>
$previous_array[description]</description>\r</item>\r\r");
}
The above code checks for the next previous date in our database, giving it the flexibility to work around holidays and weekends. It then lists that day's content ranked by popularity. The article that received the most traffic is listed first, working down to the best deals of the day, where we don't bother counting clicks.
We modify the above code once more to provide a third day in our feed, and then we close the text file.
fputs ($filepointer, "</channel>\r</rss>"); fclose ($filepointer); ?>
To read the current rss.txt file, click here. And if you're using OS X, download NetNewsWire Lite, add Low End Mac, and let software tell you when your favorite websites have new content.
As I write this, we're running the script manually, but the folks at BackBeat will be setting this up as a cron job that will automatically run every 5 minutes. This is the kind of tedium computers were designed for!
Other Updates
A couple weeks ago we changed the way we list our new content on the LEM home page. Instead of a bullet list, we display the article title using the term style (<dl>) in bold type, followed by the author, column name, and publication date in italic and a description in plain text. The latter two lines are styled as definition (<dd>).
We've received very positive feedback on the change. Here's an example from yesterday:
- Switching from Mac to Windows, really clearing a hard drive, OS X and viruses, RAM disks, and more
- Dan Knight, Low End Mac Mailbag, 02.26
- More on replacing Claris Home Page, printing from a classic Mac, getting a CD-RW drive to work with a Performa, SpamBouncer, and why some G4s won't work in G3s.
We also discovered a problem one Sunday afternoon when we discovered Monday content was being displayed below Friday's content. Looking over the PHP script, we found that we were looking for the most recent date != (PHP's way of saying "not equal") to the most recent date matching or before today's date. Changing that to < solved the problem.
I'm still far from an expert on PHP, and I'd be lost without some assistance from Dave Hamilton at BackBeat Media (they handle our ads and our servers) and two of my sons. Brian and Stephen's help has been invaluable at finding typos and other problems to crop up so easily. You'll be able to check out their programming abilities soon when the launch their third virtual pet, second robotic virtual pet, and ultimate virtual robot pet site.
Next project: Using PHP and MySQL to generate our daily news releases.
Recent Online Tech Journal Columns
- Apple's AAUI ethernet connector, 09.04. From 1991 through 1995, Apple used a proprietary ethernet connection. Why they created AAUI and where to find adapters.
- PowerPC G5: Apple's last fling with PowerPC architecture, 05.24. Teaming up with IBM, Apple adopted the PowerPC G5 in 2003 - and phased out the last G5 Power Mac three years later.
- The PowerPC G4: From 350 MHz to 2.0 GHz, 05.24. AltiVec and dual processor support made the G4 a big improvement over the earlier G3 processor.
- The PowerPC G3 story: From 233 MHz to 1.1 GHz, 05.24. The history of the PowerPC 750 family and its use in Apple computers from 1997 through 2004.
- More in the Online Tech Journal index.
Links for the Day
- Mac of the Day: Power Mac 8200, Apr. 1996 - The minitower version of 7200 was never sold in America.
- List of the Day: G4 List is for those using Power Mac G4s or G4 upgrades.
- October 6 in LEM history: 98: USB is a good thing - Can Apple save Emailer? - 99: Kihei iMacs - 00: Advice about PDS Power Macs - 03: A replacement PowerBook battery - 04: AirPort Express - 05: The Apple Lisa story - 06: Don't ignore battery recall - Use any networked computer as an additional Mac display
Recent Content on Low End Mac
- $19,800 Bentley Ego Laptop Remarkably Similar to 1999 Clamshell iBook, Charles W. Moore, Miscellaneous Ramblings, 10.06. Granted, Apple's iBook didn't have white gold trim, a padded leather exterior, or come in colors to match your Bentley automobile.
- Use Your FileMaker Pro Databases on Your iPhone, Adam Rosen, Adam's Apple, 10.06. Although there's no version of FileMaker Pro for the iPhone, FMTouch will let you use your data and layouts on it.
- The Cost of Moving to Small Business Server vs. Moving to Leopard Server., Andrew J Fishkin, Best Tools for the Job, 10.06. Upgrading the existing SBS 2003 Server would cost less, the the server will run up against hardware limitations long before a Mac Pro does.
- Best eMac Deals, Low End Mac Deals, 10.06. Used 700 MHz CD, $110; CD-RW, $130; Combo, $170; 800 CD, $170; 1 GHz Combo, $250; SuperDrive, $280; 1.25 Combo, $290; SD, $360; 1.42 Combo, $359.
- Best MacBook Air Deals, Low End Mac Deals, 10.06. Used 1.6 HD, $1,299; refurb, $1,499; new, $1,669 after rebate; 1.8, $1,919 a/r; 1.6 SSD, $2,294 a/r; used 1.8 SSD, $1,997; refurb, $2,299; new, $2,349 a/r.
- Best iPod shuffle Deals, Low End Mac Deals, 10.06. Refurb 3G/1 GB, $39; 2 GB, $59; new 1 GB (3G or 4G), $47; 2 GB (3G or 4G), $67. Prices include ground shipping.
- Mac Netbook Coming?, $179 64 GB SSD, Apple Owns 20% of US Notebook Market, and More, The 'Book Review, 10.03. Also head of Norton AntiVirus team uses a Mac, Toshiba demos new battery technology, 1 TB notebook drives due in 2010, bargain 'Books from $150 to $2,699, and more.
- Getting the Most from Your G3 Mac, Simon Royal, Mac Spectrum, 10.03. Most G3 Macs can be upgraded so they can run Mac OS X 10.4 'Tiger' quite nicely. Here's how.
- Apple Drops iPhone NDA, Defecting to Android, Auto Performance Apps for the iPhone, and More, iNews Review, 10.03. Also more research needed on cellphone cancer link, file sharing app for the iPhone, three new power accessories from Macally, several new iPhone apps, and more.
- Best Power Mac G4 and AGP Video Card Deals, Low End Mac Deals, 10.03. Used 450 MHz, $75; 500, $99; 733, $150; 800, $199; 1.25 GHz, C$349; 867 MHz dual, $225; 1 GHz, $349; 1.25, $499; 1.42, $600.
- OS X and Safari Shares Grow in September, Toxic Mac Pro?, Green Hard Drives, and More, Mac News Review, 10.03. Also Vista terrible as Mac market grows, CrossOver Mac Pro reviewed, SimpleTech Pro Drives, and a new toolkit for working on computers.
- Best iBook G3 Deals, Low End Mac Deals, 10.03. Used 300 MHz clamshell, $150; 366, $199; 500 CD, $149; 800, $190; 600 CD-RW, $240; 800 Combo, $300; 900, $399; 14" 600, $360; 900, $469.
- Best Mac OS X 10.0-10.3 Deals, Low End Mac Deals, 10.03. Mac OS X 10.0.3, $30; 10.1, $20; 10.2, $60; 10.3 CD, DVD, $100; CD, $119; 10.1 Server, unlimited users, $65; 10.3 Server, unlimited, $150.
- Why I'm Switching from Windows Small Business Server to Leopard Server, Andrew J Fishkin, Best Tools for the Job, 10.02. Windows SBS 2003 has served very well, but with SBS 2008 just around the corner, it's time to reconsider that choice. Leopard Server has a lot to offer.
- The Unwritten Rule Behind Apple's App Store Rejections, Tim Nash, Taking Back the Market, 10.02. "If you want to work with someone, don't attack or try to take over part of what they think of as theirs."
- The Best Browsers for Older Macs Running Tiger, Charles W. Moore, Miscellaneous Ramblings, 10.02. A dial-up user's overview of browsers for Mac OS X 10.4 puts the emphasis on reliability, downloads, and speed.
- Best MacBook Deals, Low End Mac Deals, 10.02. Used 1.83 GHz, $649; 2.0 SD, $750; refurb 2.1 GHz, $899; 2.4, $1,099; black, $1,299; new 2.1, $1,019 after rebate; 2.4, $1,204 a/r; black, $1,394 a/r.
- CodeWeavers Brings Google's Chrome Browser to Intel Macs, Alan Zisman, Zis Mac, 10.02. Google's new Chrome browser uses separate processes for each tab and brings other changes to Windows users. Now Mac fans can try it as well.
- Best iMac G5 Deals, Low End Mac Deals, 10.02. Used 17" 1.6 GHz Combo, $450; 2.0 SuperDrive, $500; 1.9 iSight, $625; 20" 1.8 GHz, $550; 2.0, $600; 2.1 iSight, $650.
- Best iPod touch Deals, Low End Mac Deals, 10.02. Used 1G/8 GB, $160; refurb, $179; new, $198; used 16, $200; refurb, $219; new, $265; refurb 32, $319; new, $345; 2G/8 GB, $229; 16, $280; 32, $380.
- More links in our archive.
Go to the Online Tech Journal index.
About LEM | Support | Usage | Privacy | Contacts

