如何在PHP中用新内容覆盖文件内容? [英] How can I overwrite file contents with new content in PHP?
问题描述
我尝试使用fopen,但是我仅设法将内容附加到文件末尾.可以用PHP中的新内容覆盖所有内容吗?
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?
推荐答案
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+
模式:
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'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 +'开放供阅读和写作;将文件指针放在文件的开头,并将文件截断为零长度.如果该文件不存在,请尝试创建它.
'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.
这篇关于如何在PHP中用新内容覆盖文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!