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 === "\n" || $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 !== "\n" && $char !== "\r") {
//Prepend the new character
$line = $char . $line;
fseek($f, $cursor--, SEEK_END);
$char = fgetc($f);
}
echo $line; 출력은 텍스트 파일의 마지막 라인이 읽고 표시됩니다.
텍스트 파일은 읽기 모드로 열리고 커서는 -1을 가리키도록 설정됩니다. 즉, 처음에는 아무 것도 없습니다. 'fseek' 함수는 파일의 끝 또는 마지막 줄로 이동하는 데 사용됩니다. 줄 바꿈이 발생할 때까지 줄을 읽습니다. 그 후 읽은 문자가 표시됩니다.