A script for caching and parsing RSS files using SimpleXML and php file functions


Share RSS parser with cache function ver. 1.00

released: 2008-04-30
The native function SimpleXML in PHP5 is a great functionality to parse a XML feeds as HTML show content on your website. Maybe you like to show your last blog posts on your company's website? If your website has some bigger traffic, you should think about to cache the RSS/XML file to lower the server load on the host where your RSS feed is hosted. This small PHP snippet will check if there is already a fresh cached version and if not a new feed is requested with php file functions. In that case a cache version for the new XML file is stored on the website's host. With this function the XML is stored unchanged, why? The XML has already a data structure which we use for later purposes. Using simpleXML, the XML is converted into an object and this object is used together with a loop to show some content in your HTML. In our example the RSS feed from our Wordpress weblog is parsed to show the latest posts on our website.

Viewed 8349 times

Rating: script rated with stars
 

<?php
$cache_time = 3600*24; // 24 hours

$cache_file = $_SERVER['DOCUMENT_ROOT'].'/cache/test.rss';
$timedif = @(time() - filemtime($cache_file));

if (file_exists($cache_file) && $timedif < $cache_time) {
    $string = file_get_contents($cache_file);
} else {
    $string = file_get_contents('http://www.web-development-blog.com/feed/');
    if ($f = @fopen($cache_file, 'w')) {
        fwrite ($f, $string, strlen($string));
        fclose($f);
    }
}
$xml = simplexml_load_string($string);

// place the code below somewhere in your html
echo '
<div id="rssbox">
    <ul>'
;
$count = 0;
$max = 3;
// the next object is an example for a feed from wordpress
foreach ($xml->channel->item as $val) {
    if ($count < $max) {
        echo '
        <li>
            <strong>'
.$val->title.'</strong><br />
            '
.$val->description.' | <a href="'.$val->link.'">More  &gt;</a>
        </li>'
;
    }
    $count++;
}
echo '
    </ul>
</div>'
;
?>