I'm looking to echo out some content which is collected from a source using a php class. There is no other way to obtain this content (which is just text).
Now the content is constantly changing and therefore the default function is accessing and echoing it on every page load, however I would prefer to just update it once a day but continue echoing the content every page load.
So my problem is the class file is encoded therefore I cannot make the changes that way. I was hoping I could create something that will store the text and echo the stored text until the next day where it will run the original function to get the new content.
The function that collects and echos the content:
<?php showcontent($txtonly); ?>
I would also prefer not to be placing the content within a file and getting it's contents. Hope someone can help me out :)
When you retrieve it from the source, write a text file. On each page load, check to see if the age of that file is more than one day. If it is, use the normal means to retrieve the new content and save it to the file. If it isn't older than a day, just read the local cache file and output it:
$cache_file = '/path/to/file.txt';
// Page was requested....
// It's less than a day old, just output it.
if (file_exists($cache_file) && filemtime($cache_file) > time() - 86400) {
echo file_get_contents($cache_file);
}
// It's older than a day, get the new content
else {
// do whatever you need to get the content
$content = whatever();
// Save it into the cache file
file_put_contents($cache_file, $content);
// output the new content
echo $content;
}
Note: You will need to make sure that the directory in which the cache file is stored is writable by your web server.
PHP is not "persistent" in the way you need. You can quite easily run a PHP script via cron at a certain time to fetch your changing data, but you WILL have to store that data somewhere, otherwise it's gone when this fetch script exits. The easiest is to just use a file. The fetch cript can overrite it with the new data, and your other scripts simply include/load that file whenever they run, and automatically pick up on the new data each time it changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With