gaan10
gaan10

Reputation: 77

I want to read line by line from a log file to a php file

So there is this log file that have entries saved in as line by line. Now, I want to read those and display them line by line in a php file. So far, I am able to read the file, but not able to display line by line. My php code is:

$file='/var/log/siawa/dashboard/iot.log';

$lastpos = 0;
while (true) {
    usleep(300000); //0.3 s
    clearstatcache(false, $file);
    $len = filesize($file);
    if ($len < $lastpos) {
        //file deleted or reset
        $lastpos = $len;
    }
    elseif ($len > $lastpos) {
        $f = fopen($file, "r");
        if ($f === false)
            die();
        fseek($f, $lastpos);
        while (!feof($f)) {
            $buffer = fgets($f, 4096);
            echo $buffer. "\n";
            flush();
        }
        $lastpos = ftell($f);
        fclose($f);
    }
}

These are my entries in the log file:

2016-08-17 13:21:28 | INFO: Data on Date: 2016-08-17 12:26:15 already  added
2016-08-17 13:48:46 | INFO: Data on Date: 2016-08-17 12:26:15 already  added

Upvotes: 1

Views: 247

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74230

If you looked at your HTML source during your code's execution, you would have seen that the line breaks are very well there.

What you need to do is to file_get_contents() and output it to screen with <br>.

The \n isn't enough to show them one line under the other; not on screen anyway.

Add <br> and \n in order to produce clean HTML.

echo $buffer. "<br>" . "\n";

Upvotes: 1

Related Questions