1、file_put_contents
(PHP 5, PHP 7)
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.
参数
-
要被写入数据的文件名。
-
要写入的数据。类型可以是 string,array 或者是 stream 资源(如上面所说的那样)。
如果
data
指定为 stream 资源,这里 stream 中所保存的缓存数据将被写入到指定文件中,这种用法就相似于使用 stream_copy_to_stream() 函数。参数
data
可以是数组(但不能为多维数组),这就相当于 file_put_contents($filename, join('', $array))。 -
flags
的值可以是 以下 flag 使用 OR (|) 运算符进行的组合。Available flags Flag 描述 FILE_USE_INCLUDE_PATH
在 include 目录里搜索 filename
。 更多信息可参见 include_path。FILE_APPEND
如果文件 filename
已经存在,追加数据而不是覆盖。LOCK_EX
在写入时获得一个独占锁。 -
一个 context 资源。
filename
data
flags
context
返回值
该函数将返回写入到文件内数据的字节数,失败时返回FALSE
此函数可能返回布尔值 FALSE
,但也可能返回等同于 FALSE
的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。
2、
file_get_contents
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
file_get_contents — 将整个文件读入一个字符串
说明
$filename
[,
bool $use_include_path
= false [,
resource $context
[,
int $offset
= -1 [,
int $maxlen
]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset
所指定的位置开始读取长度为 maxlen
的内容。如果失败,file_get_contents() 将返回 FALSE
。
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。
Note:
如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。
参数
-
要读取的文件的名称。
-
Note:
As of PHP 5 the
FILE_USE_INCLUDE_PATH
can be used to trigger include path search. -
A valid context resource created with stream_context_create(). 如果你不需要自定义 context,可以用
NULL
来忽略。 -
The offset where the reading starts on the original stream.
Seeking (
offset
) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream. -
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
filename
use_include_path
context
offset
maxlen
返回值
The function returns the read data 或者在失败时返回 FALSE
.