PHP – file_put_contents() 寫入檔案之前的方法 – fopen、fwrite的另外一種方式

file_put_contents() 是PHP5之後有的function 

可以快速寫入檔案,而不需要透過fopen、fwrite的傳統形式。寫起來比較簡潔快速。

原型:
file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) 
可參考PHP官方文件~

 
說明:
file_put_contents("test.txt", "一段文字"); 
 //將一段文字覆蓋寫入
test.txt 

 file_put_contents("test.txt", "\r\n新的一段文字", FILE_APPEND);  
 
 //使用 選用的參數  FILE_APPEND 可將新的一段文字寫入 test.txt的尾巴 (
\r\n 是windows的斷行符號)
 

但是沒有將新的一段文字寫入test.txt的參數
所以若要把文字寫在檔案前方就要配合 file_get_contents() 組合囉

範例:

$fname = "
test.txt ";

$str    =    file_get_contents($fname);
file_put_contents("log.txt", "新的一段文字\r\n" . $str);

 
 

發表迴響