PHP 如何在不删除的情况下将新数据添加到 .txt 的顶部

How to add new data to the top of .txt without deleting in PHP

当我使用这个代码时

$fp = fopen('data.txt', 'w');
fwrite($fp, $data);
fclose($fp);

它会覆盖文本。我也想要页脚的旧数据。那么,如何在 PHP

中不删除而将新数据添加到 .txt 的顶部

Possible output.txt and view

(new) line8
(new) line7
(new) line6
(old) line5
(old) line4
(old) line3
(old) line2
(old) line1

您可以尝试将要添加的数据与 'data.txt' 文件中的数据连接起来。

$data = "(new) line\n";
file_put_contents("data.txt", $data . file_get_contents("data.txt"));
$txt = "col1 col2 col3 coln";
file_put_contents('data.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

请试试这个。谢谢

you can use from PHP DOC file get contents and file put contents

<?php

error_reporting(E_ALL); ini_set('display_errors', 1);

$newdata = "4- whatever you need \n";
$datafromfile = file_get_contents("data.inc.txt");
file_put_contents("data.inc.txt", $newdata.$datafromfile);

?>

尝试使用 'a' 模式而不是 'w' 打开文件。

$fp = fopen('data.txt', 'a');

来自 php 手册:fopen

'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.