如何用 PHP 中的新内容覆盖文件内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7551132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I overwrite file contents with new content in PHP?
提问by newbie
I tried to use fopen, but I only managed to append content to end of file. Is it possible to overwrite all contents with new content in PHP?
我尝试使用 fopen,但我只设法将内容附加到文件末尾。是否可以用 PHP 中的新内容覆盖所有内容?
回答by Mike B
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()
可以使用w
或w+
模式:
'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.
'w+'Open for reading and writing; 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'只写;将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。
'w+'开放读写;将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。
回答by PYK
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_contentstoo: 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也是:如果您有一个大文件,它会一次性读取整个内容,并且该操作可能需要很长时间的等待时间
回答by Ram Pukar
$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);