如何使用ob_start追加到文件


How to append to file using ob_start

我已经找了一段时间了,看看如果将ob_start与PHP一起使用,是否可以"附加"到文件中。

我尝试了以下方法,但没有奏效。有什么方法可以做到这一点吗?

<?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;
}
?>

我从 S.O. 的另一篇文章中借用了上面的例子。

要使用file_put_contents()追加,您只需将FILE_APPEND作为第三个参数传递:

file_put_contents($cacheFile, $content, FILE_APPEND);

它还可用于使用二进制 OR 运算符应用文件锁定,例如 FILE_APPEND | LOCK_EX .

file_put_contents不是

这样工作的。 要追加,您需要手动使用 fopenfwritefclose

$file = fopen($cacheFile, 'a+');
fwrite($file, $content);
fclose($file);