PHP中file_put_contents追加和換行

來源:互聯網
上載者:User

標籤:open   檔案   array   ons   開啟   ever   pen   lag   everyone   

在PHP的一些應用中需要寫日誌或者記錄一些資訊,這樣的話。可以使用fopen(),fwrite()以及 fclose()這些進行操作。也可以簡單的使用file_get_contents()和file_put_contents().

file_put_contents()寫檔案。預設的是重新寫檔案,也就是會 替換原先的內容。追加的話使用參數FILE_APPEND.

以追加形式寫入內容 當設定 flags 參數值為 FILE_APPEND 時,表示在已有檔案內容後面追加內容的方式寫入新資料:

FILE_APPEND:在檔案末尾以追加的方式寫入資料

 

int file_put_contents ( string filename, string data [, int flags [, resource context]] )  file_put_contents ( "log.txt" , "Hello world everyone." , FILE_APPEND);  //參數說明: //參數    說明 filename    //要寫入資料的檔案名稱 data    //要寫入的資料。類型可以是 string,array(但不能為多維陣列),或者是 stream 資源 flags   //可選,規定如何開啟/寫入檔案。可能的值: FILE_USE_INCLUDE_PATH: //檢查 filename 副本的內建路徑 FILE_APPEND: //在檔案末尾以追加的方式寫入資料 LOCK_EX: //對檔案上鎖 context //可選,Context是一組選項,可以通過它修改文字屬性

很多時候記錄日誌需要換行。不建議使用\r\n,因為:
在windows中\r\n是換行
在Mac中\r是換行
在Liunx中\n是換行

但是PHP提供了一個常量來匹配不同的作業系統,即:

PHP_EOL file_put_contents ( "log.txt" , "Hello world everyone." .PHP_EOL, FILE_APPEND);

PHP中file_put_contents追加和換行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.