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);