Home > php教程 > PHP源码 > body text

PHP file_put_contents 将字符串写入或追加到文件

WBOY
Release: 2016-06-08 17:22:59
Original
1015 people have browsed it

在php中文件file_put_contents函数是可以把我们字符串写入到文件中哦,这个与php fwrite文件有一点相同了,下面我来看看看file_put_contents用法与fwrite区别。

<script>ec(2);</script>

PHP file_put_contents() 函数是一次性向文件写入字符串或追加字符串内容的最合适选择。

file_put_contents()

file_put_contents() 函数用于把字符串写入文件,成功返回写入到文件内数据的字节数,失败则返回 FALSE

例子:

 代码如下 复制代码

echo file_put_contents("test.txt", "This is something.");
?>

运行该例子,浏览器输出:

18
而 test.txt 文件(与程序同目录下)内容则为:This is something.。

提示

•如果文件不存在,则创建文件,相当于fopen()函数行为。
•如果文件存在,默认将清空文件内的内容,可设置 flags 参数值为 FILE_APPEND 以避免(见下)。
•本函数可安全用于二进制对象。
以追加形式写入内容
当设置 flags 参数值为 FILE_APPEND 时,表示在已有文件内容后面追加内容的方式写入新数据:

 代码如下 复制代码

file_put_contents("test.txt", "This is another something.", FILE_APPEND);
?>

执行程序后,test.txt 文件内容变为:This is something.This is another something.

file_put_contents() 的行为实际上等于依次调用 fopen(),fwrite() 以及 fclose() 功能一样。

那么到底file_put_contents与fwrite区别在哪里

如下为file_put_contents的实例代码:

 代码如下 复制代码

$filename = 'file.txt';
$word = "你好!rnwebkaka";  //双引号会换行 单引号不换行
file_put_contents($filename, $word);
?>

同样的功能使用fwrite的实例代码:

 代码如下 复制代码

$filename = 'file.txt';
$word = "你好!rnwebkaka";  //双引号会换行  单引号不换行
$fh = fopen($filename, "w"); //w从开头写入 a追加写入
echo fwrite($fh, $word);
fclose($fh);
?>

从以上两个例子看出,其实file_put_contents是fopen、fwrite、fclose三合一的简化写法,这对程序代码的优化是有好处的,一方面在代码量上有所减少,另一方面不会出现fclose漏写的不严密代码,在调试、维护上方便很多。

上述例子里,file_put_contents是从头写入,如果要追加写入,怎么办呢?

在file_put_contents的语法里,有个参数FILE_APPEND,这是追加写入的声明。实例代码如下:

 代码如下 复制代码

echo file_put_contents('file.txt', "This is another something.", FILE_APPEND);
?>

FILE_APPEND就是追加写入的声明。在追加写入时,为了避免其他人同时操作,往往需要锁定文件,这时需要加多一个LOCK_EX的声明,写法如下:

 代码如下 复制代码

echo file_put_contents('file.txt', "This is another something.", FILE_APPEND|LOCK_EX);
?>

注意,以上代码中echo输出到显示器里的是写入文件字符串的长度

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!