简体   繁体   中英

Cache RSS feed using PHP?

I am currently displaying several RSS feeds but it causes the website to load slow and occasionally not load properly if a feed doesn't load. I am using PHP to display the feed with an example of the code I am using below:

<?php
 error_reporting(0);
 $rss = new DOMDocument();
 $rss->load('http://www1.skysports.com/feeds/11677/news.xml');
 $feed = array();



 foreach ($rss->getElementsByTagName('item') as $node) {
    $item = array (
                    'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                    'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                    'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,



    );
    array_push($feed, $item);
 }
 $limit = 2;
 for($x=0;$x<$limit;$x++) {
    $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
    $link = $feed[$x]['link'];
    $date = date('l F d, Y', strtotime($feed[$x]['date']));

    echo '<div id="wholefeed"><div id="feed"><img src="img/SkySports.png" alt="logo" class="logo"><div id="rsstext"><a target="_blank" href="'.$link.'" title="'.$title.' ">'.$title.'</a></div></a></div></div>';

 }
?>

To help with this I would like to store it in a cache and have it check every hour or so. How can I go about doing this?

Thanks.

I recommend you to use Memcache for PHP , a distributed cache system in RAM. This solution is fast and handles any data type.

Furthermore, Memcache is easy to use. You could modify your code as follows:

<?php
    // Connect to Memcache server
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die ("Could not connect");

    // Get feed data from Memcache
    $feed = $memcache->get('KEY_FOR_FEED_DATA');
    if($feed === false) {
        // The 'KEY_FOR_FEED_DATA' key has expired. You have to get
        // the feed data again

        // code to get the $feed variable

        // Save feed data to Memcache
        $memcache->set('KEY_FOR_FEED_DATA', $feed, false, EXPIRE_TIME);
    }

    // Here you have the $feed variable
?>

You only have to specify the EXPIRE_TIME in 3600 (seconds in an hour)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM