I'm a newbie that's having a bit of trouble figuring out PHP. I've made it a long way and I've read a lot of manual pages and tutorials. Some of this code is mine and some of it I got from the manual pages, so it's a Frankenstein script. Believe me, if I could have found the code to do this, I would have taken it in a second. But I couldn't find it so I had to write and piece together something that would work. Sadly, this represents about 60 hours of work.
The code below fetches a remote page, stores it, scans it for the desired text and then displays the desired text in a webpage. It also checks to see if the stored file is "old" and if so, updates the stored file. It "works", but I believe it could be more efficient and I'm sure I've made some very rookie mistakes.
Anyway, one 'bug' is, if the file doesn't exist, the display is empty, if it's the first time the file is called. Any call after the file is created displays and updates normally. This isn't really a problem as I'm not going to delete the file, but it's a bug regardless.
Anyway, take a look at the code and let me know if there's something I can do to make it work.... better.
<?php
$url = "http://somesite.com/index.php"; //url of remote site
$cache_time = 5; //time in seconds
$myfile = "tmp/123.txt"; //local file - path needs to be relative to the file that calls it!
$modified = @filemtime($myfile);
$now = strtotime("now");
$difference = $now - $modified; // how old is the file
$start = ' meters ('; // starting to get data after this string
$end = ' feet)'; //stop getting data before this
$start2 = 'Mean Period</td><td>'; // starting to get data after this string
$end2 = 'seconds</td></tr>'; //stop getting data before this
$data = file_get_contents('tmp/123.txt'); //local file - path needs to be relative to the file that calls it!
//if the file is older than cache_time rewrite it
if ($difference >= $cache_time)
{
$fh = fopen($myfile, 'w') or die("File Error");
$stringData = file_get_contents("$url","r");
fwrite($fh, $stringData);
fclose($fh);
}
//it works without the "else" but it seems fater with it - I don't know
//read the local file and print the desired output
if(($pos = strpos($data, $start)) !== false) {
$data = substr($data, $pos);
if(($pos = strpos($data, $end)) !== false) {
echo strip_tags(str_replace($start, '', substr($data, 0, $pos)));
echo ' ft. @ ';
if(($pos2 = strpos($data, $start2)) !== false) {
$data = substr($data, $pos2);
if(($pos2 = strpos($data, $end2)) !== false) {
echo strip_tags(str_replace($start2, '', substr($data, 0, $pos2)));
echo ' sec';
}
}
}
}
?>
comments and suggestions welcome!
EDIT: changed to PHP tags