(PHP 5)
file_put_contents — 將一個字符串寫入文件
說明
int file_put_contents ( string$filename
, mixed $data
[, int $flags
= 0
[, resource $context
]] )
和依次調用 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
此函數可能返回布爾值
FALSE
,但也可能返回等同于 FALSE
的非布爾值。請閱讀 布爾類型章節以獲取更多信息。應使用
===
運算符來測試此函數的返回值。
范例
Example #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 Smithn";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Example #2 Using flags
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smithn";
// 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 資源的功能。
注釋
Note: 此函數可安全用于二進制對象。
Tip如已啟用fopen 包裝器,在此函數中, URL 可作為文件名。關于如何指定文件名詳見 fopen()。各種 wapper 的不同功能請參見 支持的協議和封裝協議,注意其用法及其可提供的預定義變量。
參見
fopen() - 打開文件或者 URL fwrite() - 寫入文件(可安全用于二進制文件) file_get_contents() - 將整個文件讀入一個字符串 stream_context_create() - 創建資源流上下文