php 文件写入

来源:互联网 发布:sql查询表列名 编辑:程序博客网 时间:2024/06/10 20:59

比如我们要操作的文件是demo.txt

一种方式是 

$file = fopen('demo.txt','a');

$content = 'xxxxxxxx';

fwrite($file,$content);

fclose($file);

有时文件写入写出比较频繁,防止写入失败,可以使用

flock($file,LOCK_EX);

flock($file,LOCK_UN);


另一种方式

使用file_put_contents();

if(file_exists('demo.txt')){

                        $str = 'xxxxx';
$fp = 'demo.txt';
$fcontent = $str."\r\n";
file_put_contents($fp,$fcontent,FILE_APPEND | LOCK_EX);
}else{
echo 'the file does not exist';
}


需要注意的是要写入的文件路径是绝对路径,可以运用__FILE__获得





0 0