简体   繁体   中英

Cache an XML feed from a remote URL

Im using a remote xml feed, and I don't want to hit it every time. This is the code I have so far:

$feed = simplexml_load_file('http://remoteserviceurlhere');
if ($feed){
  $feed->asXML('feed.xml');
}
elseif (file_exists('feed.xml')){
    $feed = simplexml_load_file('feed.xml');
}else{
    die('No available feed');
}

What I want to do is have my script hit the remote service every hour and cache that data into the feed.xml file.

<?php

$cache = new JG_Cache();
if(!($feed = $cache->get('feed.xml', 3600))) {
     $feed = simplexml_load_file('http://remoteserviceurlhere');
     $cache->set('feed.xml', $feed);
}

Use any file based caching mechanism eg http://www.jongales.com/blog/2009/02/18/simple-file-based-php-cache-class/

Here is a simple solution:

Check the last time your local feed.xml file was modified. If the difference between the current timestamp and the filemtime timestamp is greater than 3600 seconds, update the file:

$feed_updated = filemtime('feed.xml');
$current_time = time();

if($current_time - $feed_updated >= 3600) {

         // Your sample code here...

} else {

       // use cached feed...
}
$feedmtime = filemtime('feed.xml');
$current_time = time();
if(!file_exists('feed.xml') || ($current_time - $feedmtime >= 3600)){
    $feed = simplexml_load_file($url);
    $feed->asXML('feed.xml');
 }else{
    $feed = simplexml_load_file('feed.xml');
 }
 return $feed;

I created a simple PHP class to tackle this issue. Since I'm dealing with a variety of sources, it can handle whatever you throw at it (xml, json, etc). You give it a local filename (for storage purposes), the external feed, and an expires time. It begins by checking for the local file. If it exists and hasn't expired, it returns the contents. If it has expired, it attempts to grab the remote file. If there's an issue with the remote file, it will fall-back to the cached file.

Blog post here: http://weedygarden.net/2012/04/simple-feed-caching-with-php/ Code here: https://github.com/erunyon/FeedCache

看一下Simple PHP缓存

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