Filesystem 函数
PHP Manual

fgets

(PHP 4, PHP 5)

fgets从文件指针中读取一行

说明

string fgets ( int $handle [, int $length ] )

handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。

出错时返回 FALSE

通常的缺陷:

习惯了 C 语言中 fgets() 语法的人应该注意到 EOF 是怎样被返回的。

文件指针必须是有效的,必须指向由 fopen()fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

以下是一个简单例子:

Example #1 逐行读取文件

<?php
$handle 
= @fopen("/tmp/inputfile.txt""r");
if (
$handle) {
    while (!
feof($handle)) {
        
$buffer fgets($handle4096);
        echo 
$buffer;
    }
    
fclose($handle);
}
?>

Note: length 参数从 PHP 4.2.0 起成为可选项,如果忽略,则行的长度被假定为 1024。从 PHP 4.3 开始,忽略掉 length 将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8KB,则在脚本中指定最大行的长度在利用资源上更为有效。

Note: 从 PHP 4.3 开始本函数可以安全用于二进制文件。早期的版本则不行。

Note: 在读取在 Macintosh 电脑中或由其创建的文件时, 如果 PHP 不能正确的识别行结束符,启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

参见 fgetss()fread()fgetc()stream_get_line()fopen()popen()fsockopen()stream_set_timeout()

参数

handle

文件指针必须是有效的,必须指向由 fopen()fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

length

Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.

Note:

Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.

返回值

Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned.

If an error occurs, FALSE is returned.

更新日志

版本 说明
4.3.0 fgets() is now binary safe
4.2.0 The length parameter became optional

范例

Example #2 Reading a file line by line

<?php
$handle 
= @fopen("/tmp/inputfile.txt""r");
if (
$handle) {
    while ((
$buffer fgets($handle4096)) !== false) {
        echo 
$buffer;
    }
    if (!
feof($handle)) {
        echo 
"Error: unexpected fgets() fail\n";
    }
    
fclose($handle);
}
?>

注释

Note: 在读取在 Macintosh 电脑中或由其创建的文件时, 如果 PHP 不能正确的识别行结束符,启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

Note:

People used to the 'C' semantics of fgets() should note the difference in how EOF is returned.

参见


Filesystem 函数
PHP Manual