简体   繁体   English

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

[英]How can I overwrite file contents with new content in PHP?

I tried to use fopen, but I only managed to append content to end of file. 我试图使用fopen,但我只设法将内容附加到文件末尾。 Is it possible to overwrite all contents with new content in PHP? 是否可以用PHP中的新内容覆盖所有内容?

Use file_put_contents() 使用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

Alternatively, if you're stuck with fopen() you can use the w or w+ modes: 或者,如果你坚持使用fopen()你可以使用ww+模式:

'w' Open for writing only; 'w'仅供写作; 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. 如果该文件不存在,请尝试创建它。

'w+' Open for reading and writing; 'w +'开放阅读和写作; 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. 如果该文件不存在,请尝试创建它。

$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);

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU] 我首选的方法是使用fopen,fwrite和fclose [它会花费更少的CPU]

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

Warning for those using file_put_contents 对于那些使用file_put_contents的人的警告

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time 它会影响很多性能,例如[在相同的类/情况下] file_get_contents :如果你有一个BIG FILE,它会一次性读取整个内容,并且该操作可能需要很长的等待时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM