Derrick
Derrick

Reputation: 69

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.

Upvotes: 2

Views: 5172

Answers (5)

Felipe Oliveira
Felipe Oliveira

Reputation: 11

$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;

Upvotes: 1

Erik Runyon
Erik Runyon

Reputation: 81

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

Upvotes: 0

Anthony
Anthony

Reputation: 37065

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...
}

Upvotes: 4

fire
fire

Reputation: 21531

Take a look at Simple PHP caching.

Upvotes: 0

Ish
Ish

Reputation: 29546

<?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 e.g. http://www.jongales.com/blog/2009/02/18/simple-file-based-php-cache-class/

Upvotes: 4

Related Questions