file_get_contents()
把整个文件读成一个字符串,也支持直接读 URL。
file_get_contents(string $filename, bool $use_include_path = false, ?resource $context = null, int $offset = 0, ?int $length = null): string|false
参数
| 参数 | 类型 | 说明 |
|---|---|---|
$filename | string | 文件路径或 URL |
$use_include_path | bool | 是否在 include_path 中查找 |
$context | resource | 流上下文,用于设置请求头、超时 |
$offset | int | 从第几个字节开始读 |
$length | ?int | 读多少字节 |
返回值
string|false — 文件内容,失败返回 false。
示例
$txt = file_get_contents(__DIR__ . '/data.txt');
echo strlen($txt) . ' 字节';注意
- 读大文件会把整个内容放进内存,几百 MB 会打满 memory_limit,改用 fopen + fgets。
- 失败时返回 false 并抛 Warning,用 @ 抑制后要自己判断返回值。
- 读远程 URL 需要 allow_url_fopen=On,生产环境建议改用 curl 并设超时。