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

时间:2011-09-26 06:00:11

标签: php file

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

3 个答案:

答案 0 :(得分:67)

使用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(),则可以使用ww+模式:

  

'w'仅限写作;将文件指针放在文件的开头,并将文件截断为零长度。如果该文件不存在,请尝试创建它。

     

'w +'开放阅读和写作;将文件指针放在文件的开头,并将文件截断为零长度。如果该文件不存在,请尝试创建它。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

我首选的方法是使用 fopen,fwrite和fclose [它会花费更少的CPU]

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

使用 file_put_contents

的警告

它会影响很多性能,例如[在同一类/情况下] file_get_contents :如果你有一个大文件,它会读取整个内容一次性操作可能需要很长的等待时间