phpday 2027 - Call for Papers

fgets

(PHP 4, PHP 5, PHP 7, PHP 8)

fgets — ファイルポインタから 1 行取得する

説明

function fgets(resource $stream, ?int $length = null): string|false

ファイルポインタから 1 行取得します。

パラメータ

stream

ファイルポインタは、有効なファイルポインタである必要があり、 fopen() または fsockopen() で正常にオープンされた (そしてまだ fclose() でクローズされていない) ファイルを指している必要があります。

length

読み出しは、length - 1 バイト読み出したか、(戻り値に含まれる) 改行文字を検出したか、EOF に達したかのいずれかが起こった時点で終了します。 length が指定されない場合は、行末に達するまで読み続けます。

戻り値

stream で指定したファイルポインタから最大 length - 1 バイト読み出し、 その文字列を返します。ファイルポインタから読み込むデータがもうない場合は false を返します。

エラーが起こった場合、false を返します。

例

例1 行毎にファイルを読み込む

<?php

$fp = @fopen("/tmp/inputfile.txt", "r");

if ($fp) {
    while (($buffer = fgets($fp, 4096)) !== false) {
        echo $buffer, PHP_EOL;
    }

    if (!feof($fp)) {
        echo "Error: unexpected fgets() fail\n";
    }

    fclose($fp);
}

?>

注意

注意:

PHP 8.1.0 より前のバージョンでは、実行時の設定オプション auto_detect_line_endings を有効にすることで、Macintosh 系のシステムで作成されたファイルの行末を PHP に正しく認識させることができました。このオプションは PHP 8.1.0 で非推奨になりました。 必要な場合は、代わりに "\r" の改行を手動で処理してください。

注意:

C 言語の fgets() の動作に慣れている人は、 EOF を返す条件の違いについて注意する必要があります。

参考

  • fgetss() - ファイルポインタから 1 行取り出し、HTML タグを取り除く
  • fread() - バイナリセーフなファイルの読み込み
  • fgetc() - ファイルポインタから1文字取り出す
  • stream_get_line() - 指定されたデリミタの位置までのデータを一行分としてストリームから読み込む
  • fopen() - ファイルまたは URL をオープンする
  • popen() - プロセスへのファイルポインタをオープンする
  • fsockopen() - インターネット接続もしくは Unix ドメインソケット接続をオープンする
  • stream_set_timeout() - ストリームにタイムアウトを設定する

User Contributed Notes 5 notes

up
16
Leigh Purdie
11 years ago
A better example, to illustrate the differences in speed for large files, between fgets and stream_get_line.

This example simulates situations where you are reading potentially very long lines, of an uncertain length (but with a maximum buffer size), from an input source.

As Dade pointed out, the previous example I provided was much to easy to pick apart, and did not adequately highlight the issue I was trying to address.

Note that specifying a definitive end-character for fgets (ie: newline), generally decreases the speed difference reasonably significantly. 

#!/usr/bin/php
<?php
        $plaintext=file_get_contents('http://loripsum.net/api/60/verylong/plaintext');  # Should be around 90k characters
        $plaintext=str_replace("\n"," ",$plaintext); # Get rid of newlines

        $fp=fopen("/tmp/SourceFile.txt","w");
        for($i=0;$i<100000;$i++) {
                fputs($fp,substr($plaintext,0,rand(4096,65534)) . "\n");
        }
        fclose($fp);

        $fp=fopen("/tmp/SourceFile.txt","r");
        $start=microtime(true);
        while($line=fgets($fp,65535)) {
                1;
        }
        $end=microtime(true);
        fclose($fp);
        $delta1=($end - $start);

        $fp=fopen("/tmp/SourceFile.txt","r");
        $start=microtime(true);
        while($line=stream_get_line($fp,65535)) {
                1;
        }
        $end=microtime(true);
        fclose($fp);
        $delta2=($end - $start);

        $pdiff=$delta1/$delta2;
        print "stream_get_line is " . ($pdiff>1?"faster":"slower") . " than fgets - pdiff is $pdiff\n";
?>

$ ./testcase.php 
stream_get_line is faster than fgets - pdiff is 1.760398041785

Note that, in a vast majority of situations in which php is employed, tiny differences in speed between system calls are of negligible importance.
up
4
Anonymous
6 years ago
if you for some reason need to get lines from a string instead of a file pointer, try

<?php
function string_gets(string $source, int $offset = 0, string $delimiter = "\n"): ?string
{
    $len = strlen($source);
    if ($len < $offset) {
        // out of bounds.. maybe i should throw an exception
        return null;
    }
    if ($len === $offset) {
        // end of string..
        return null;
    }
    $delimiter_pos = strpos($source, $delimiter, $offset);
    if ($delimiter_pos === false) {
        // last line.
        return substr($source, $offset);
    }
    return substr($source, $offset, ($delimiter_pos - $offset) + strlen($delimiter));
}

?>

(i had a ~16GB string in-memory i needed to process line-by-line, but i would get memory-allocation-crash (on a 32GB ram system) if i tried explode("\n",$str); , so came up with this.. interestingly, fgets() seems to be faster than doing it in-ram-in-php, though. php 7.3.7)
up
4
David at Weintraub.name
19 years ago
There's an error in the documentation:

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

You should also add "popen" and "pclose" to the documentation. I'm a new PHP developer and went to verify that I could use "fgets" on commands that I used with "popen".
up
1
Peter Schlaile
19 years ago
fscanf($file, "%s\n") isn't really a good substitution for fgets(), since it will stop parsing at the first whitespace and not at the end of line!

(See the fscanf page for details on this)
up
-2
tavernadelleidee[italy]
20 years ago
I think that the quickest way of read a (long) file with the rows in  reverse order is

<?php
$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
passthru($command);
$ic = 0;
$ic_max = 100;  // stops after this number of rows
$handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && ++$ic<=$ic_max) {
   $buffer = fgets($handle, 4096);
   echo $buffer."<br>";
}
fclose($handle);
?>

It echos the rows while it is reading the file so it is good for long files like logs.

Borgonovo
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top