PHP 寫入文件 file_put_contents
2009年11月17日
尚無評論
在 PHP 版本 5.0.0 之前 file_put_contents 這個函數,必須使用fwrite寫法。
1 2 3 4 5 6 | <?php $fp = fopen("data.txt","w"); //必須要先用fopen開啟文件 $string = "Hello World"; //字串 fwrite($fp, $string); //用fwrite寫入 fclose($fp); //關閉檔案 ?> |
使用 file_put_contents
1 2 3 4 5 | <?php $fp="data.txt"; $string = "Hello World"; //字串 file_put_contents($fp, $string); ?> |
fwrite 寫入文件未端,只要把 $mode 參數 w 改成 a 就好。
1 2 3 4 5 6 | <?php $fp = fopen("data.txt","a"); //必須要先用fopen開啟文件 $string = "Hello World"; //字串 fwrite($fp, $string); //用fwrite寫入 fclose($fp); //關閉檔案 ?> |
由於 file_put_contents 沒有 $mode 參數可以設定,所以需要使用 file_get_contents 取得文件內容。
1 2 3 4 5 6 | <?php $fp="data.txt"; $string=file_get_contents($fp); //先取出文件內容,轉成字串 $string.="Hello World"; //在字串最後加入新字串 file_put_contents($fp, $string); //寫入文件 ?> |
