0

I'm trying to cache the contents of an XML file, so that only one request per day to the external server is required. Basically, if the locally created XML file is more than a day old, to get the external contents and replace the contents of the local file.

However, I don't think the logic to working out the time difference is right, as I think (just in my head), my condition below is going to take effect if time() plus one day in seconds, is larger than the time the file was created... which it always will be (I think).

Can anyone help me understand what this is doing, and why it may not be working as expected?

$original_xml = '#####';
$new_xml      = get_template_directory().'/inc/horoscopes.xml';
$ageInSeconds = 86400; // 1 day

if(!file_exists($new_xml) || filemtime($new_xml) < time() + $ageInSeconds) {
    $contents = file_get_contents($original_xml);
    file_put_contents($new_xml, $contents);
}
Lee
  • 4,187
  • 6
  • 25
  • 71

1 Answers1

0

The current time plus one day, whatever the unit, is tomorrow so I'd expect your file to always have a creation time earlier than that.

I don't know the details of the language or functions you are using so I'm assuming that filemtime() and time() return a time offset in seconds.

All you need to do is subtract a day instead of adding it, e.g.

if(!file_exists($new_xml) || filemtime($new_xml) < (time() - $ageInSeconds))

I've added brackets to (time() - $ageInSeconds) for clarity but they probably aren't necessary.

spodger
  • 1,668
  • 1
  • 12
  • 16