PHP file_get_contents详解和使用示例

作者:IT技术圈子 浏览量:95   发表于 2024-08-02 09:19 标签:

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contents — 将整个文件读入一个字符串

说明

file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
): string|false

和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 length 的内容。如果失败,file_get_contents() 将返回 false

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

参数

filename

要读取的文件的名称。

use_include_path

context

stream_context_create() 创建的有效的上下文(context)资源。 如果你不需要自定义 context,可以用 null 来忽略。

offset

读取原始数据流的开始位置偏移量。负的 offset 会从数据流的末尾开始统计。

远程文件不支持偏移量寻址(offset)。 对远程文件以较小的 offset 可能可以正常寻址, 但由于是对缓冲流进行操作,所以操作结果不可预测。

length

要读取数据的最大长度。 默认情况下会读到文件末尾。 注意,该参数会应用到处理 stream 的过滤器(filter)中。

返回值

函数返回读取到的数据, 或者在失败时返回 false


错误/异常

以下情况会导致 E_WARNING 级别错误: 无法找到 filename 文件; length 小于零; 在 steam 中无法寻址偏移量 offset

Windows 下用 file_get_contents() 读取目录会导致 E_WARNING 错误。 PHP 7.4 起,其他操作系统也会出现同样错误。

示例

示例 #1 获取并输出网站首页 HTML 源码

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

示例 #2 在 include_path 里搜索

<?php
// 如果开启了严格类型,例如 declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// 否则就这样写
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

示例 #3 读取文件一小节

<?php
// 从第 21 个字符开始,读取 14 字符长度
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>

以上示例的输出类似于:

string(14) "lle Bjori Ro"

示例 #4 使用 stream 上下文(context)

<?php
// 创建 stream
$opts = array(
 'http'=>array(
 'method'=>"GET",
 'header'=>"Accept-language: en\r\n" .
 "Cookie: foo=bar\r\n"
 )
);

$context = stream_context_create($opts);

// 以下面设置的 HTTP 头来打开文件
$file = file_get_contents('http://www.example.com/', false, $context);
?>