如何将文本附加到文件末尾上方15行的位置


How to append text to a file a 15 lines above its end

我正在尝试使用fwrite()将HTML添加到文件中。我的最终目标是让它在文件末尾上方添加15行。以下是我目前所拥有的:

<?php 
    $file = fopen("index.html", "r+");
    // Seek to the end
    fseek($file, SEEK_END, 0);
    // Get and save that position
    $filesize = ftell($file);
    // Seek to half the length of the file
    fseek($file, SEEK_SET, $filesize + 15);
    // Write your data
    $main = <<<MAIN
    //html goes here
    MAIN;
     fwrite($file, $main);
    // Close the file handler
    fclose($file);
?>

这只是不断覆盖文件的顶部。谢谢

问题中的示例代码不是基于行操作的,因为您使用的是文件大小(除非对应用程序中的行定义有一个假设,但这里没有提到)。如果你想处理行,那么你需要搜索新的行字符(将每一行与下一行分隔开)。

如果目标文件不是一个大文件(因此我们可以将整个文件加载到内存中),我们可以使用PHP内置的file()将文件的所有行读取到一个数组中,然后在第15个元素之后插入数据。像这样的东西:

<?php
$lines = file($filename);
$num_lines = count($lines);
if ($num_lines > 15) {
    array_splice($lines, $num_lines - 15, 0, array($content));
    file_put_contents($filename, implode('', $lines));
} else {
    file_put_contents($filename, PHP_EOL . $content, FILE_APPEND);
}