I have a file named file.txt
which is update by adding lines to it.
I am reading it by this code:
$fp = fopen("file.txt", "r"); $data = ""; while(!feof($fp)) { $data .= fgets($fp, 4096); } echo $data;
and a huge number of lines appears. I just want to echo the last 5 lines of the file
How can I do that ?
The file.txt
is like this:
11111111111111 22222222222 33333333333333 44444444444 55555555555555 66666666666
The 'fseek' function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.
To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.
If you ABSOLUTELY know the file exists, you can use a one-liner: $line = fgets(fopen($file, 'r')); The reason is that PHP implements RAII for resources. That means that when the file handle goes out of scope (which happens immediately after the call to fgets in this case), it will be closed.
PHP Close File - fclose() The fclose() function is used to close an open file.
For a large file, reading all the lines into an array with file() is a bit wasteful. Here's how you could read the file and maintain a buffer of the last 5 lines:
$lines=array(); $fp = fopen("file.txt", "r"); while(!feof($fp)) { $line = fgets($fp, 4096); array_push($lines, $line); if (count($lines)>5) array_shift($lines); } fclose($fp);
You could optimize this a bit more with some heuristics about likely line length by seeking to a position, say, approx 10 lines from the end, and going further back if that doesn't yield 5 lines. Here's a simple implementation which demonstrates that:
//how many lines? $linecount=5; //what's a typical line length? $length=40; //which file? $file="test.txt"; //we double the offset factor on each iteration //if our first guess at the file offset doesn't //yield $linecount lines $offset_factor=1; $bytes=filesize($file); $fp = fopen($file, "r") or die("Can't open $file"); $complete=false; while (!$complete) { //seek to a position close to end of file $offset = $linecount * $length * $offset_factor; fseek($fp, -$offset, SEEK_END); //we might seek mid-line, so read partial line //if our offset means we're reading the whole file, //we don't skip... if ($offset<$bytes) fgets($fp); //read all following lines, store last x $lines=array(); while(!feof($fp)) { $line = fgets($fp); array_push($lines, $line); if (count($lines)>$linecount) { array_shift($lines); $complete=true; } } //if we read the whole file, we're done, even if we //don't have enough lines if ($offset>=$bytes) $complete=true; else $offset_factor*=2; //otherwise let's seek even further back } fclose($fp); var_dump($lines);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With