What is the issue with the code provided for reading the last 200 lines of a file in PHP?
The issue with the code provided is that it reads the entire file into an array, which may not be memory efficient for large files. To read only the last 200 lines of a file efficiently, you can seek to the end of the file, backtrack to find the start of the last 200 lines, and then read those lines.
$file = "example.txt";
$lines = 200;
$handle = fopen($file, "r");
$line_count = 0;
$pos = -2;
$beginning = false;
while ($line_count < $lines) {
$t = " ";
while ($t != "\n") {
fseek($handle, $pos, SEEK_END);
$t = fgetc($handle);
$pos--;
if ($pos < -filesize($file)) {
fseek($handle, 0);
$beginning = true;
break;
}
}
$line_count++;
if ($beginning) {
rewind($handle);
}
}
while ($line = fgets($handle)) {
echo $line;
}
fclose($handle);
Keywords
Related Questions
- How can PHP beginners handle server limitations when it comes to installing extensions like SimpleXML?
- How can PHP developers optimize their code by avoiding excessive use of escape characters in form elements?
- How can PHP scripts be triggered to execute actions based on incoming files in a specific directory?