Return to Snippet

Revision: 57752
at June 8, 2012 09:23 by crypticsoft


Initial Code
function get_news($url=''){

//save the rss file cache
$validCache = false;
if (file_exists('rss_cache.txt')) {
    $contents = file_get_contents('rss_cache.txt');
    $data = unserialize($contents);
    if (time() - $data['created'] < 24 * 60 * 60) {
        $validCache = true;
        $feed = $data['feed'];
    }
}

if (!$validCache) {

    $feed = file_get_contents($url);
    $data = array ('feed' => $feed, 'time' => time() );
    file_put_contents('rss_cache.txt', serialize($data));
}

	//get the xml object
	$news = new SimpleXMLElement(trim($feed));

	$result = array();
	foreach($news->channel->item as $item){
		$result[] = array(
			'title' => $item->title,
			'link' => $item->link,
			'description' => trim($item->description)
		);
	}
	return $result;

}
function display_news($news, $limit=3){
	
	print "<ul class='news-feed'>";
	$cnt = 0;
	foreach($news as $n){
		if($cnt == $limit) return;
		print '<li class="news-item"><a href="' . $n['link'][0] . '" target="_blank">' . $n['title'][0] . '</a><p>';
		print $n['description'] . ' <a href="' . $n['link'][0] . '" target="_blank"><strong>read more</strong> &raquo;</a>';
		print '</li>';
		$cnt++;
	}

	print '</ul>';

}

Initial URL
http://stackoverflow.com/questions/6176561/caching-a-wordpress-rss-feed-with-php

Initial Description
Note: This also uses a flat file to cache the results, be sure to also upload the 'rss_cache.txt' file. 

Usage:
<?php>

Initial Title
RSS Feed Caching

Initial Tags
file, wordpress

Initial Language
PHP