如何在PHP中用新内容覆盖文件内容? [英] How can I overwrite file contents with new content in PHP?

查看:522
本文介绍了如何在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_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+模式:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆