file_get_contents
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
file_get_contents — 将整个文件读入一个字符串
说明
string file_get_contents
( string $filename
[, bool $use_include_path
= false
[, resource $context
[, int $offset
= -1
[, int $maxlen
]]]] )
file_get_contents()
函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。
Note:
如果要打开有特殊字符的 URL (比如说有空格),就需要使用
urlencode() 进行 URL 编码。
参数
-
filename
-
要读取的文件的名称。
-
use_include_path
-
Note:
As of PHP 5 the FILE_USE_INCLUDE_PATH
can be used
to trigger include path
search.
-
context
-
A valid context resource created with
stream_context_create().
如果你不需要自定义 context,可以用 NULL
来忽略。
-
offset
-
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.
-
maxlen
-
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.
返回值
The function returns the read data 或者在失败时返回 FALSE
.
错误/异常
An E_WARNING
level error is generated if either maxlength
is less than zero, or if seeking to the specified offset
in the stream fails.
范例
Example #1 Get and output the source of the homepage of a website
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Example #2 Searching within the include_path
<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Example #3 Reading a section of a file
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
注释
Note: 此函数可安全用于二进制对象。
Warning使用 SSL 时,Microsoft IIS
会违反协议不发送close_notify标记就关闭连接。PHP 会在到达数据尾端时报告"SSL: Fatal Protocol Error"。
要解决此问题,error_reporting 应设定为降低级别至不包含警告。
PHP 4.3.7 及更高版本可以在使用 https:// 包装器打开流时检测出有问题的 IIS 服务器软件 并抑制警告。在使用
fsockopen() 创建 ssl:// 套接字时, 开发者需检测并抑制此警告。