根据巴巴的回答修改;此代码将在文件开头写入新行,并将擦除最后一行以始终保持 3 行。
<?php
function addNew($fileName, $line, $max) {
// Remove Empty Spaces
$file = array_filter(array_map("trim", file($fileName)));
// Make Sure you always have maximum number of lines
$file = array_slice($file, 0, --$max);
// Remove any extra line and adding the new line
count($file) >= $max and array_unshift($file, $line);
// Save Result
file_put_contents($fileName, implode(PHP_EOL, array_filter($file)));
}
// Number of lines
$max = 3;
// The file must exist with at least 2 lines on it
$file = "log.txt";
addNew($file, "New Line at : " . time(), $max);
?>