file_put_contents
(PHP 5, PHP 7, PHP 8)
file_put_contents — 將一個字串寫入檔案
說明
和依次呼叫 fopen(),fwrite() 以及 fclose() 功能一樣。
If filename
does not exist, the file is created.
Otherwise, the existing file is overwritten, unless the
FILE_APPEND
flag is set.
參數
-
filename
-
要被寫入數據的檔名。
-
data
-
要寫入的數據。型別可以是 string,array 或者是 stream 資源(如上面所說的那樣)。
如果
data
指定為 stream 資源,這裡 stream 中所儲存的快取數據將被寫入到指定檔案中,這種用法就相似於使用 stream_copy_to_stream() 函式。參數
data
可以是陣列(但不能為多維陣列),這就相當於file_put_contents($filename, join('', $array))
。 -
flags
-
flags
的值可以是 以下 flag 使用 OR (|
) 運算子進行的組合。Available flags Flag 描述 FILE_USE_INCLUDE_PATH
在 include 目錄里搜索 filename
。 更多資訊可參見 include_path。FILE_APPEND
如果檔案 filename
已經存在,追加數據而不是覆蓋。LOCK_EX
在寫入時獲得一個獨佔鎖。 -
context
-
一個 context 資源。
返回值
該函式將返回寫入到檔案內數據的位元組數,失敗時返回false
範例
示例 #1 Simple usage example
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
示例 #2 Using flags
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
更新日誌
版本 | 說明 |
---|---|
5.0.0 | Added context support |
5.1.0 |
新增了對 LOCK_EX 的支援和 data
參數處理 stream 資源的功能。
|
註釋
注意: 此函式可安全用於二進制對象。
如已啟用fopen 包裝器,在此函式中, URL 可作為檔名。關於如何指定檔名詳見 fopen()。各種 wapper 的不同功能請參見 支援的協議和封裝協議,注意其用法及其可提供的預定義變數。
參見
- fopen() - 打開檔案或者 URL
- fwrite() - 寫入檔案(可安全用於二進制檔案)
- file_get_contents() - 將整個檔案讀入一個字串
- stream_context_create() - 建立資源流上下文