PHP fgets() 関数


❮ 完全な PHP ファイルシステム・リファレンス

定義と用法

fgets() 関数は、オープンしているファイルから1行返します。

fgets() 関数は、改行、指定した長さ、または EOF のいずれか早い方を検出した時に読込みを停止します。

この関数は、失敗した場合にはFALSEを返します。

構文

fgets(file,length)

パラメータ 説明
file 必須。読み込むファイルを指定する
length 任意。読み込むバイト数を指定する。デフォルトは 1024 バイト。


例 1

<?php
$file = fopen("test.txt","r");
echo fgets($file);
fclose($file);
?>

上のコードの出力は、次の通り:

Hello, this is a test file.

例 2

Read file line by line:

<?php
$file = fopen("test.txt","r");

while(! feof($file))
  {
  echo fgets($file). "<br />";
  }

fclose($file);
?>

上のコードの出力は、次の通り:

Hello, this is a test file.
There are three lines here.
This is the last line.

❮ 完全な PHP ファイルシステム・リファレンス