在 PHP 中讀取檔案最後一行


要從檔案讀取 PHP 的最後一行,程式碼如下所示 −

$line = '';
$f = fopen('data.txt', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);
//Trim trailing newline characters in the file
while ($char === "
" || $char === "\r") {    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f); } //Read until the next line of the file begins or the first newline char while ($char !== false && $char !== "
" && $char !== "\r") {    //Prepend the new character    $line = $char . $line;    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f); } echo $line;

輸出將是讀取並顯示文字檔案的最後一行。

文字檔案以讀取模式開啟,並且游標設定為指向 -1,即最初什麼都不指向。‘fseek’ 函式用於移動到檔案或最後一行末尾。該行讀取直到遇到換行符。此後,顯示讀取的字元。

更新於: 09-4-2020

3k+ 瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.