I have looked for quite a while now, to see if it's possible to "append" to a file if using ob_start with PHP.
I have tried the following but did not work. Any way of achieving this?
<?php
$cacheFile = 'file.txt';
if ( (file_exists($cacheFile)) && ((fileatime($cacheFile) + 600) > time()) )
{
$content = file_get_contents($cacheFile);
echo $content;
} else
{
ob_start();
// write content
echo '<h1>Hello world</h1>';
$content = ob_get_contents();
ob_end_clean();
file_put_contents($cacheFile,$content,'a+'); // I added the a+
echo $content;
}
?>
I borrowed the above example from another post on S.O.
The ob_start() function creates an output buffer. A callback function can be passed in to do processing on the contents of the buffer before it gets flushed from the buffer. Flags can be used to permit or restrict what the buffer is able to do.
Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it. This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).
Delete an output buffer and send its contents to the browser: ob_start(); echo "This output will be sent to the browser"; ob_end_flush();
The ob_end_clean() function deletes the topmost output buffer and all of its contents without sending anything to the browser.
To append using file_put_contents()
you can simply pass FILE_APPEND
as the third argument:
file_put_contents($cacheFile, $content, FILE_APPEND);
It can also be used to apply file locking using the binary OR operator, e.g. FILE_APPEND | LOCK_EX
.
file_put_contents
doesn't work that way. To append, you need to use fopen
, fwrite
and fclose
manually.
$file = fopen($cacheFile, 'a+');
fwrite($file, $content);
fclose($file);
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