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\");
$da
Least amount of ram, and outputs well. I agree with Paul Dixon...
$lines=array();
$fp = fopen("userlog.txt", "r");
while(!feof($fp))
{
$line = fgets($fp, 4096);
array_push($lines, $line);
if (count($lines)>25)
array_shift($lines);
}
fclose($fp);
while ($a <= 10) {
$a++;
echo "<br>".$lines[$a];
}
If your lines are separated by a CR or LF you would try exploding your $data variable:
$lines = explode("\n", $data);
$lines should end up being an array and you can work out the number of records using sizeof() and just get the last 5.
This is a common interview question. Here's what I wrote last year when I was asked this question. Remember that code you get on Stack Overflow is licensed with the Creative Commons Share-Alike with attribution required.
<?php
/**
* Demonstrate an efficient way to search the last 100 lines of a file
* containing roughly ten million lines for a sample string. This should
* function without having to process each line of the file (and without making
* use of the “tail” command or any external system commands).
* Attribution: https://stackoverflow.com/a/2961731/3389585
*/
$filename = '/opt/local/apache2/logs/karwin-access_log';
$searchString = 'index.php';
$numLines = 100;
$maxLineLength = 200;
$fp = fopen($filename, 'r');
$data = fseek($fp, -($numLines * $maxLineLength), SEEK_END);
$lines = array();
while (!feof($fp)) {
$lines[] = fgets($fp);
}
$c = count($lines);
$i = $c >= $numLines? $c-$numLines: 0;
for (; $i<$c; ++$i) {
if ($pos = strpos($lines[$i], $searchString)) {
echo $lines[$i];
}
}
This solution does make an assumption about the maximum line length. The interviewer asked me how I would solve the problem if I couldn't make that assumption, and had to accommodate lines that were potentially longer than any max length I chose.
I told him that any software project has to make certain assumptions, but I could test if $c
was less than the desired number of lines, and if it isn't, fseek()
back further incrementally (doubling each time) until we do get enough lines.
$dosya = "../dosya.txt";
$array = explode("\n", file_get_contents($dosya));
$reversed = array_reverse($array);
for($x = 0; $x < 6; $x++)
{
echo $reversed[$x];
}
If you're on a linux system you could do this:
$lines = `tail -5 /path/to/file.txt`;
Otherwise you'll have to count lines and take the last 5, something like:
$all_lines = file('file.txt');
$last_5 = array_slice($all_lines , -5);
You can use my small helper library (2 functions)
https://github.com/jasir/file-helpers
Then just use:
//read last 5 lines
$lines = \jasir\FileHelpers\FileHelpers::readLastLines($pathToFile, 5);