Latest web development tutorials

PHP fgets() 函數

PHP Filesystem 參考手冊 完整的PHP Filesystem參考手冊

定義和用法

fgets() 函數從打開的文件中返回一行。

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

按行讀取文件:

<?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 Filesystem 參考手冊 完整的PHP Filesystem參考手冊