在PHP中附加到文件的开头

Som*_*Som 3 php

嗨,我想使用PHP在文件的开头追加一行.

让我们说例如该文件包含以下contnet:

    Hello Stack Overflow, you are really helping me a lot.
Run Code Online (Sandbox Code Playgroud)

现在我想在这样的反复上面添加一行:

    www.stackoverflow.com
    Hello Stack Overflow, you are really helping me a lot.
Run Code Online (Sandbox Code Playgroud)

这是我目前在脚本中拥有的代码.

    $fp = fopen($file, 'a+') or die("can't open file");
    $theOldData = fread($fp, filesize($file));
    fclose($fp);

    $fp = fopen($file, 'w+') or die("can't open file");
    $toBeWriteToFile = $insertNewRow.$theOldData;
    fwrite($fp, $toBeWriteToFile);
    fclose($fp);
Run Code Online (Sandbox Code Playgroud)

我想要一些最佳解决方案,因为我在PHP脚本中使用它.以下是我在这里找到的一些解决方案: 需要用PHP在文件开头写

在开头追加以下内容:

    <?php
    $file_data = "Stuff you want to add\n";
    $file_data .= file_get_contents('database.txt');
    file_put_contents('database.txt', $file_data);
    ?>
Run Code Online (Sandbox Code Playgroud)

另外一个在这里: 使用php,如何插入文本而不覆盖文本文件的开头

说如下:

    $old_content = file_get_contents($file);
    fwrite($file, $new_content."\n".$old_content);
Run Code Online (Sandbox Code Playgroud)

所以我的最后一个问题是,这是上述所有方法中使用的最佳方法(我的意思是最佳).有可能比上面更好吗?

寻找你对此的看法!!!

vde*_*nne 6

function file_prepend ($string, $filename) {

  $fileContent = file_get_contents ($filename);

  file_put_contents ($filename, $string . "\n" . $fileContent);
}
Run Code Online (Sandbox Code Playgroud)

用法:

file_prepend("couldn't connect to the database", 'database.logs');
Run Code Online (Sandbox Code Playgroud)


Dal*_*ale 1

写入文件时我个人的偏好是使用file_put_contents

从手册中:

该函数与依次调用 fopen()、fwrite() 和 fclose() 将数据写入文件相同。

因为该函数会自动为我处理这三个函数,所以我不必记住在完成资源后关闭资源。