用PHP编写TXT文件,想在开头插入新行

是否可以在 .txt 文件的开头插入新行?

我了解到 usingfwrite(filename, sentence)是在末尾添加一个新行。

但我想知道是否有任何方法可以在开头添加新行,就像我原来的 .txt 文件是

AAA

当我添加一个新行“BBB”时,它看起来像

BBB
AAA


阿晨1998
浏览 286回答 1
1回答

墨色风雨

您可以file_get_contents()先使用获取原始数据,然后将字符串添加到该数据之前:$existing = file_get_contents('/path/to/file.txt');$fp = fopen('/path/to/file.txt', 'w');    $myString = 'hello world'. PHP_EOL;fwrite($fp, $myString. $existing);fclose($fp);在这里,我们用 - 打开文件w以完全覆盖,而不是追加。因此,我们需要在fopen(). 然后我们获取现有文件内容并将其连接到您的字符串,并覆盖文件。编辑:file_put_contents() - 正如 Nigel Ren 所建议的那样$existing = file_get_contents('/path/to/file.txt');$myString = 'hello world'. PHP_EOL;file_put_contents('/path/to/file.txt', $myString. $existing);编辑:创建单线的功能function prepend_to_file(string $file, string $data){    if (file_exists($file)) {        try {            file_put_contents($file, $data. file_get_contents($file));            return true;        } catch (Exception $e) {            throw new Exception($file. ' couldn\'t be amended, see error: '. $e->getMessage());        }    } else {        throw new Exception($file. ' wasn\'t found. Ensure it exists');    }}# then use:if (prepend_to_file('/path/to/file.txt', 'hello world')) {    echo 'prepended!';}
打开App,查看更多内容
随时随地看视频慕课网APP