PHP使用file_put_contents写入文件的优点

本篇文章由:http://xinpure.com/advantages-of-php-file-write-put-contents-to-a-file/

写入方法的比较

先来看看使用 fwrite 是如何写入文件的

$filename = 'HelloWorld.txt';
$content = 'Hello World!';
$fh = fopen($filename, "w");
echo fwrite($fh, $content);
fclose($fh);

再看看使用 file_put_contents 是如何写入文件的

$filename = 'HelloWorld.txt';
$content = 'Hello World!';
file_put_contents($filename, $content);

以上我们可以看出,file_put_contents 一行就代替了 fwrite 三行代码,

可见其优点: 简洁、易维护,也不会出现,因 fclose() 忘写的不严密行为。

方法进阶

追加写入

file_put_contents 写入文件时,默认是从头开始写入,如果需要追加内容呢?

file_put_contens 方法里,有个参数 FILE_APPEND,这是追加写入文件的声明。

file_put_contents(HelloWorld.txt, 'Hello World!', FILE_APPEND);

锁定文件

在写入文件时,为避免与其它人同时操作,通常会锁定此文件,这就用到了第二个参数: LOCK_EX

file_put_contents(HelloWorld.txt, 'Hello World!', FILE_APPEND|LOCK_EX);

此外,为了确保正确写入,通常会先判断该文件是否可写

if (is_writable('HelloWorld.txt')) {
    file_put_contents(HelloWorld.txt, 'Hello World!', FILE_APPEND|LOCK_EX);
}
原文地址:https://www.cnblogs.com/xinpureZhu/p/4326039.html