php写入、追加写入文件的实例

本文深入讲解了使用PHP进行文件操作的方法,包括如何使用fopen()函数创建或打开文件,fwrite()函数写入内容,以及fclose()函数关闭文件流。特别介绍了在文件存在时追加内容,不存在时创建文件的技巧。
1 $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
2 $txt = "Bill Gates\n";
3 fwrite($myfile, $txt);
4 $txt = "Steve Jobs\n";
5 fwrite($myfile, $txt);
6 //记得关闭流
7 fclose($myfile);

 

fopen() 函数也用于创建文件。也许有点混乱,但是在 PHP 中,创建文件所用的函数与打开文件的相同。

如果您用 fopen() 打开并不存在的文件,此函数会创建文件,假定文件被打开为写入(w)或增加(a)。

判断文件是否存在,不存在就创建,存在就追加

 

 1         if(file_exists('notify.txt'))
 2         {
 3             //"当前目录中,文件存在",追加
 4             $myfile = fopen("notify.txt", "a") or die("Unable to open file!");
 5             $txt = "\n【".date('Y-m-d H:i:s',time())."】---"."成功回调";
 6             fwrite($myfile, $txt);
 7             //记得关闭流
 8             fclose($myfile);
 9         }
10         else
11         {
12             //"当前目录中,文件不存在",新写入
13             $myfile = fopen("notify.txt", "w") or die("Unable to open file!");
14             $txt = "【".date('Y-m-d H:i:s',time())."】---"."成功回调";
15             fwrite($myfile, $txt);
16             //记得关闭流
17             fclose($myfile);
18         }    

 

或者用a+模式,比如这样:

1 $myfile = fopen("notify_error.log", "a+") or die("Unable to open file!");
2 $txt = "【".date('Y-m-d H:i:s',time())."】---".$rec"\r\n";
3 fwrite($myfile, $txt);
4 //记得关闭流
5 fclose($myfile);

 

转载于:https://www.cnblogs.com/njflash/p/10484326.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值