[thelist] Using PHP to read and cache XML feed

Pringle, Ron RPringle at aurora-il.org
Fri Oct 20 13:52:36 CDT 2006

Thanks to Matt for pointing me in the general direction, despite my
highly inaccurate description of what I was attempting to do. I did
manage to come up with the following code, below.

Basically I'm checking if a file exists, if it doesn't I create it and
write data to it from an external XML file located on the National
Weather Service's site. If it does exist, I check to see if it is an
hour or more old, and if it is I overwrite it with new data. If not, I
use the existing file.

Currently I'm just doing an XSL transformation on the XML file, but I
may try to step through it in PHP and output it that way.

I may also try to implement caching of the data once it is local, since
it will get called over and over again and the data only changes once
per hour.

So, in looking over the code I have below, is there a better way to do
it, or anything that I have missed?


// Get Weather Routine //
$filename = 'sample.xml';
$weatherdata =
fopen("http://www.nws.noaa.gov/data/current_obs/sample.xml", "rb");

// check to see if the local file exists
if (file_exists($filename)) {
	// get difference in seconds between now and last modified date
	$diff = (time() - filemtime("$filename"))/60*60;
	// if greater than 1 hr (3600 seconds) get new file from source
	if ($diff >= 3600) {
		file_put_contents($filename,$weatherdata, LOCK_EX);
	} else {
	// file doesn't exist, get data and create new file //
	file_put_contents($filename,$weatherdata, LOCK_EX);

More information about the thelist mailing list