Jane
Jane

Reputation: 987

Caching xml data from remote server

Let's say I'm using simpleXML to parse weather data from a remote server, and then the remote server crashes so I can no longer recover its live feeds but I don't want my users to get an error message either, how would I go about caching and continuing to display the last piece of data I got from the server before it crashed?

Let's say my xml looks like this:

<weather>
    <temperature c="25" f="77">
</weather>

How would I go about displaying the values "25" and "77" until I'm able to reestablish a connection with the remote server?

Apologies if my question isn't entirely clear... my knowledge of server-side technologies is very limited.

Upvotes: 1

Views: 414

Answers (3)

cweiske
cweiske

Reputation: 31098

First: You do not want to fetch the remote data live when the user requests your site. That works for small sites with few visitors when no problems occur, but as soon as the remote server hangs, your site will also hang until the connection timeout occurs.

What we mostly do is the following:

  • Create a script that fetches the remote file and stores it locally in some temporary folder. If the remote file cannot be fetched, do not overwrite the old one. This is very important, and @Drazisil code does exactly this.
  • Call that script with a cron job, or at the end of your normal script every x minutes
  • Use the local file when creating your normal HTML output instead of the remote one.

In the end, your pages will always be delivered fast and will not crash when the remote server is down.

Upvotes: 2

Drazisil
Drazisil

Reputation: 3343

This isn't the best way, but here is one way you could do it:

To save the information

$file = 'temp_cache.php';
// Open the file to get existing content
$content = '<?php $c="25"; $f="77"; ?>';
// Write the contents to the file
file_put_contents($file, $content);

To load it

include_once('temp.php');

By including the file, your $c and $f variables will be set unless you overwrite them.

Upvotes: 1

Kinexus
Kinexus

Reputation: 12904

Store the values locally and display this information to your users. Update when you want, in such a way that it will only overwrite the local copy when successful; If it fails, you will have your 'local' copy.

Upvotes: 1

Related Questions