Load RSS Feeds into PHP Arrays with lastRSS
Published: January 6th, 2009 by: Andrew
RSS Feeds are a great way to keep up with the latest news and blog sites, but we can also use them to bring data into our PHP applications. In this article, I will show you how to load any RSS feed into variables that you can manage in PHP.
We are going to be using Snoopy and lastRSS, so go ahead and download both of those scripts and extract the class files to a place where you can include them.
The lastRSS script is what we will be using to parse the RSS feeds. This class does work with remote files, such as http://phpstarter.net/feed/, but it can only do it using PHP’s remote file open option, not cURL. All you have to know about this problem is that it doesn’t work on all servers, because many have “remote file open” disabled for security purposes. I covered Snoopy in a previous article, and we learned that it does support cURL. We will be using Snoopy to download the remote feed and save it locally. Then, lastRSS will open the local file and parse the feed. It won’t sound that hard when you see the example.
In the following example, I load a remote feed and echo the titles & links to the browser.
<?php
/* there is no need to call the feed up every time, so we will cache it locally for 1 hour */
if (!file_exists('feed.cache') || filemtime('feed.cache') + 3600 < time())
{
/**
* Looks like we don't have a recent copy, so we will use Snoopy to fetch the remote feed.
* See: http://phpstarter.net/2008/12/how-to-post-data-and-fetch-remote-pages-from-php-scripts/
*/
require('../includes/Snoopy.class.php');
$snoopy = new Snoopy();
/* set this to the RSS feed where we want to fetch the data from */
$snoopy->fetch('http://phpstarter.net/feed/');
/* save this to a local cache file so the RSS feed isn't called too often */
file_put_contents('feed.cache', $snoopy->results);
}
/**
* We will use lastRSS to parse the feed.
* See: http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/
*/
require('../includes/lastRSS.php');
$rss = new lastRss();
/* load the cached file */
$feed = $rss->get('feed.cache');
?>
<html>
<head>
<title>lastRSS & Snoopy Example</title>
</head>
<body>
<?php foreach ($feed['items'] as $field => $item) : ?>
<a href="<?=$item['link']?>"><p><?=$item['title']?></p></a>
<?php endforeach; ?>
</body>
</html>
It’s pretty simple and straight forward. Your results may vary based on your hosting environment. If you run into a snag, please post a comment, and I should be able to help.
Related posts:


xSaimex
Apr 20th, 2009
7:51 pm
Hi,
nice tutorial! I was wondering if it’s possible to save all the data to a external file? Like all the latest news to something like blah.txt, so it nevers gets deleted. If so, could you do an example please?