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

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         }    

猜你喜欢

转载自www.cnblogs.com/njflash/p/10484326.html