PHP fwrite() 函数与 file_put_contents() 函数的比较

两个 PHP 函数都可以把字符串保存到文件中,fwrite() 函数的格式是:

int fwrite ( resource handle , string string [ , int length] )

它只能写入字符串

 

file_put_contents() 函数的格式是:

int file_put_contents ( string $filename, mixed $data [, int $flags [, resource $context]] )

其中 file 是文件路径,data 可以是字符串,可以是一维数组或二维数组,不能是多维数组

 

两种方法当要写入的文件不存在时,都会自动创建文件。当文件存在时, 根据使用 fwrite() 函数之前使用 fopen() 函数打开文件资源的模式,或者使用 file_put_contents() 函数的第三个参数来确定写入文件的模式:

例如

使用 fopen() , fwrite() , fclose() 这一系列函数时

<?php

$filename = "data.txt";

$handle = fopen($filename,"w") or die("打开".$filename."文件失败");

$str = "updating your profile with your name";

fwrite($handle,$str);

fclose($handle);

就相当于 file_put_contents() 的

<?php

$filename = "data.txt";

$str = "updating your profile with your name";

file_put_contents($filename,$str);

将原本需要 3 行代码的地方简化到了 1 行。

 

当需要追加写入文件时,fopen() , fwrite() , fclose() 的

<?php

$filename = "data.txt";

$handle = fopen($filename,"a") or die("打开".$filename."文件失败");

$str = "updating your profile with your name";

fwrite($handle,$str);

fclose($handle);

就相当于 file_put_contents() 的

<?php

$filename = "data.txt";

$str = "updating your profile with your name";

file_put_contents($filename,$str,FILE_APPEND);

另外为了避免多人同时操作文件,可以增加文件的锁声明:

file_put_contents($filename,$str,FILE_APPEND|LOCK_EX);

 

效率:file_put_contents() 函数与依次调用 fopen() , fwrite() , fclose() 的功能一样,也就是说,file_put_contents() 在写入每条数据时,都要打开和关闭资源,而使用 fopen()、 fwrite() 、fclose() 时,只需要一次打开资源和一次关闭资源关闭,效率上使用 fopen()、 fwrite() 、fclose() 更快,适用于处理大量数据;如果处理的数据量不多,为了代码简洁可以使用file_put_contents() 函数。

posted @ 2014-10-27 22:48  nemo20  阅读(1161)  评论(0编辑  收藏  举报
访客数:AmazingCounters.com
2016/05/17 起统计