Friday, March 20

Don't ask questions you already know the answer to - REST apis part 3

Okay, let's have a look at something else.

You probably don't want to go trawling for data every time you need to process some, so let's look at saving some data.

State your REST source as usual, but instead of a simplexml load, do:

$somefile=fopen($somecall,"r");
file_put_contents("somedata.xml",$somefile);
fclose($somefile);

Which loads your resource, saves it to the server as xml (or whatever), then closes the connection. That's all you need to put it this file - end with ?> as usual and save as whatever - fetchdata.php

Then, whenever you need to refresh your source: include("fetchdata.php");

Whenever you want to use the data that's already there:

$sxmlobject = simplexml_load_file("somedata.xml");

if it's XML. If you have to deal with JSON you can still loop if you use an array, instead of a simplexml load.

Here's one last trick. On your main page, you can make it refresh the data in time intervals. Or specifically, you tell it to refresh if it's been at least X mins/hours/days since the last refresh.



//This function refreshes the data and records the time it does it.
function refreshData()
{
$t = time();
include("fetchdata.php");
file_put_contents("lastupdate.txt",$t);
}

//This is now
$timenow = time();

//If you can't find that record, refresh anyway. This is so it works first time!
if(!file_exists("lastupdate.txt"))
{
refreshData();
}

//Find out the last time you refreshed - might have been just a few lines above though!
$timeload = file_get_contents("lastupdate.txt");

//If it's been 10 hours - 36000 seconds - since refresh, refresh!
if ($timenow > $timeload + 36000)
{
refreshData();
}

$sxmlobject = simplexml_load_file("somedata.xml");
//and do something with it!

?>

No comments:

Post a Comment