PHP fgets 函数
最后修改于 2025 年 4 月 3 日
PHP fgets 函数从文件指针读取一行。 它通常用于在 PHP 应用程序中逐行读取文件。
基本定义
fgets 函数从文件指针读取最多 length - 1 字节。 当读取了 length - 1 字节,或者遇到换行符时,读取停止。
语法:fgets(resource $stream, ?int $length = null): string|false。 该函数返回读取的字符串,或者在失败时返回 false。
fgets 基本示例
这展示了使用 fgets 逐行读取文件的最简单用法。
basic_fgets.php
<?php
declare(strict_types=1);
$file = fopen("example.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
这打开 "example.txt" 并逐行读取它,直到 EOF。 每行末尾都包含换行符。 始终使用 fclose 关闭文件。
读取特定长度
第二个参数限制从行中读取多少个字节。
fgets_length.php
<?php
declare(strict_types=1);
$file = fopen("example.txt", "r");
if ($file) {
$line = fgets($file, 10);
echo $line;
fclose($file);
}
这从第一行读取最多 9 个字节(10 - 1)。如果该行较短,则在换行符处停止。 length 参数是可选的。
读取 CSV 文件
fgets 可以与 str_getcsv 结合使用来解析 CSV。
csv_reader.php
<?php
declare(strict_types=1);
$file = fopen("data.csv", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
$fields = str_getcsv($line);
print_r($fields);
}
fclose($file);
}
这逐行读取 CSV 文件,并将每一行解析成一个字段数组。 fgets 的换行符由 str_getcsv 处理。
错误处理
在使用文件操作时,适当的错误处理很重要。
error_handling.php
<?php
declare(strict_types=1);
$filename = "nonexistent.txt";
$file = @fopen($filename, "r");
if ($file === false) {
echo "Failed to open file: $filename";
exit(1);
}
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
这展示了打开文件时的适当错误处理。 @ 抑制警告,允许自定义错误处理。 始终检查 false 返回值。
读取远程文件
当启用 allow_url_fopen 时,fgets 可以从远程文件读取。
remote_file.php
<?php
declare(strict_types=1);
$url = "https://example.com/data.txt";
$file = fopen($url, "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo htmlspecialchars($line);
}
fclose($file);
}
这逐行读取远程文件。 请注意,htmlspecialchars 在输出远程内容时防止 XSS。 检查 PHP 配置。
最佳实践
- 资源管理: 始终使用
fclose关闭文件。 - 错误处理: 检查文件操作的 false 返回值。
- 内存效率: 对大型文件使用
fgets。 - 安全性: 验证/清理文件路径和内容。
- 性能: 考虑对频繁的小型读取进行缓冲。
来源
本教程介绍了 PHP fgets 函数,并提供了实际示例,展示了它在不同文件读取场景中的用法。
作者
列出 所有 PHP 文件系统函数。