如何用 PHP 中的新内容覆盖文件内容?

我尝试使用 fopen,但只能将内容附加到文件的末尾。是否可以用 PHP 中的新内容覆盖所有内容?

140940 次浏览

使用 file_put_contents()

file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo

或者,如果你被 fopen()卡住了,你可以使用 w或者 w+模式:

‘ w’ 打开只供写入; 将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。

“ w +” 打开以进行读写操作; 将文件指针放在文件的开头,并将文件截断为零长度。如果该文件不存在,请尝试创建它。

$fname = "database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("192.168.1.198", "localhost", $content);


$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);

我的首选方法是使用 Fopen,fwrite 和 fclose[它将花费较少的 CPU ]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

对使用 File _ put _ content的用户发出警告

它会对性能产生很大的影响,例如[在相同的类/情况下] File _ get _ content: 如果您有一个 BIG FILE,它将一次读取整个内容,这个操作可能需要很长的等待时间