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         }    

 

或者用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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM