PHP Conference Japan 2024

SplFileObject::fgets

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fgets從檔案取得一行

說明

public SplFileObject::fgets(): 字串

從檔案取得一行。

參數

此函式沒有參數。

回傳值

回傳一個字串,包含檔案中的下一行。

錯誤/例外

如果檔案無法讀取,則拋出 RuntimeException

範例

範例 #1 SplFileObject::fgets() 範例

此範例簡單地逐行輸出 file.txt 的內容。

<?php
$file
= new SplFileObject("file.txt");
while (!
$file->eof()) {
echo
$file->fgets();
}
?>

另請參閱

新增註釋

使用者貢獻的註釋 3 則註釋

Lucas Bustamante
3 年前
請注意,在 PHP 8.0.10 中,`fgets` 在 `seek` 之後的行為發生了變化。如果您搜尋到第 50 行並執行 `fgets`,它會返回第 50 行,而在 PHP 5.1~8.0.0 中,它會返回第 51 行。

<?php

$file
= new SplTempFileObject();

for (
$i = 0; $i < 100; $i++) {
$file->fwrite("Foo $i\n");
}

$file->seek(50);

echo
json_encode(array(
array(
'line' => $file->key(), 'contents' => trim($file->fgets())),
array(
'line' => $file->key(), 'contents' => trim($file->fgets())),
array(
'line' => $file->key(), 'contents' => trim($file->fgets())),
),
JSON_PRETTY_PRINT);

?>

結果

PHP 8.0.1+
[
{
"line": 50,
"contents": "Foo 50"
},
{
"line": 50,
"contents": "Foo 51"
},
{
"line": 51,
"contents": "Foo 52"
}
]

PHP 5.1 至 8.0.0
[
{
"line": 50,
"contents": "Foo 51"
},
{
"line": 51,
"contents": "Foo 52"
},
{
"line": 52,
"contents": "Foo 53"
}
]
Chris Johnson
6 年前
請注意,如果正在讀取的檔案不包含可識別的換行字元,並且大小超過 PHP 可分配的記憶體大小(例如 php.ini 或類似檔案中設定的 memory_limit),則此方法將導致 PHP 嚴重錯誤。換句話說,PHP 會持續讀取直到找到換行字元,如果先耗盡記憶體,則會拋出嚴重錯誤。

這與檔案資源 fread() 函式不同,fread() 函式允許傳遞一個可選的最大長度參數來限制此行為。
Lucas Bustamante
3 年前
我忘了在我之前關於 PHP 8.0.10 的說明中提到,您可以使用 $file->current(); $file->next(); 來取代 $file->fgets();,在 seek() 之後,這個方法在 PHP 5.1 到 8.0.1+ 版本中都能一致地運作。

<?php

$file
= new SplTempFileObject();

for (
$i = 0; $i < 100; $i++) {
$file->fwrite("Foo $i\n");
}

$file->seek(50);

print_r(array(
array(
'line' => $file->key(), 'contents' => trim($file->current()), 'triggerNext' => $file->next()),
array(
'line' => $file->key(), 'contents' => trim($file->current()), 'triggerNext' => $file->next()),
array(
'line' => $file->key(), 'contents' => trim($file->current()), 'triggerNext' => $file->next()),
));

?>

PHP 5.1 至 8.0.1+

[
{
"line": 50,
"contents": "Foo 50"
},
{
"line": 51,
"contents": "Foo 51"
},
{
"line": 52,
"contents": "Foo 52"
}
]
To Top