file_put_contents
(PHP 5, PHP 7, PHP 8)
file_put_contents — 将数据写入文件
说明
string
$filename,mixed
$data,int
$flags = 0,?resource
$context = null): int|false
和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。
如果 filename
不存在,将会创建文件。反之,存在的文件将会重写,除非设置
FILE_APPEND flag。
参数
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在写入时获取文件独占锁。换句话说,在调用 fopen() 和 fwrite() 中间发生了 flock() 调用。这与调用带模式“x”的 fopen() 不同。 context-
一个 context 资源。
返回值
该函数将返回写入到文件内数据的字节数,失败时返回false
示例
示例 #1 简单用法示例
<?php
$file = 'people.txt';
// 打开文件获取已经存在的内容
$current = file_get_contents($file);
// 追加新成员到文件
$current .= "John Smith\n";
// 将内容写回文件
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);
?>注释
注意: 此函数可安全用于二进制对象。
如已启用fopen 包装器,在此函数中, URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议,注意其用法及其可提供的预定义变量。
参见
- fopen() - 打开文件或者 URL
- fwrite() - 写入文件(可安全用于二进制文件)
- file_get_contents() - 将整个文件读入一个字符串
- stream_context_create() - 创建资源流上下文