file_put_contents

(PHP 5, PHP 7, PHP 8)

file_put_contents將一個(gè)字符串寫入文件

說明

file_put_contents(
    string $filename,
    mixed $data,
    int $flags = 0,
    resource $context = ?
): int

和依次調(diào)用 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.

參數(shù)

filename

要被寫入數(shù)據(jù)的文件名。

data

要寫入的數(shù)據(jù)。類型可以是 string,array 或者是 stream 資源(如上面所說的那樣)。

如果 data 指定為 stream 資源,這里 stream 中所保存的緩存數(shù)據(jù)將被寫入到指定文件中,這種用法就相似于使用 stream_copy_to_stream() 函數(shù)。

參數(shù) data 可以是數(shù)組(但不能為多維數(shù)組),這就相當(dāng)于 file_put_contents($filename, join('', $array))

flags

flags 的值可以是 以下 flag 使用 OR (|) 運(yùn)算符進(jìn)行的組合。

Available flags
Flag 描述
FILE_USE_INCLUDE_PATH 在 include 目錄里搜索 filename。 更多信息可參見 include_path
FILE_APPEND 如果文件 filename 已經(jīng)存在,追加數(shù)據(jù)而不是覆蓋。
LOCK_EX 在寫入時(shí)獲得一個(gè)獨(dú)占鎖。

context

一個(gè) context 資源。

返回值

該函數(shù)將返回寫入到文件內(nèi)數(shù)據(jù)的字節(jié)數(shù),失敗時(shí)返回false

警告

此函數(shù)可能返回布爾值 false,但也可能返回等同于 false 的非布爾值。請(qǐng)閱讀 布爾類型章節(jié)以獲取更多信息。應(yīng)使用 === 運(yùn)算符來測(cè)試此函數(shù)的返回值。

范例

示例 #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$personFILE_APPEND LOCK_EX);
?>

更新日志

版本 說明
5.0.0 Added context support
5.1.0 添加了對(duì) LOCK_EX 的支持和 data 參數(shù)處理 stream 資源的功能。

注釋

注意: 此函數(shù)可安全用于二進(jìn)制對(duì)象。

小技巧

如已啟用fopen 包裝器,在此函數(shù)中, URL 可作為文件名。關(guān)于如何指定文件名詳見 fopen()。各種 wapper 的不同功能請(qǐng)參見 支持的協(xié)議和封裝協(xié)議,注意其用法及其可提供的預(yù)定義變量。

參見