Question

I am trying to append to a log file, using HTML tables format for each incident. However, there is one difficulty which I am not sure how to solve. Here's a static output of the HTML

<table>
  <tr><td> .... </td>
  </tr>

 <!-- new log entry should enter here -->

  </table>
</html>

The question is how I can quickly insert log entries into the table quickly without messing up the HTML, preferably using the least amount of processing? I know I can load in the entire file, use a templating solution, and rewrite the file but that may be slow (the log files could grow fast quickly!).

So I am looking for the usual open file for append, and somehow write after the last row, but before the tag.

Any suggestions?

PS. I know most browser would render the HMTL if I leave out the tag at the end, but I am curious to see if there could be an ideal solution.

Was it helpful?

Solution

I'd suggest creating the log file with just the table rows, then including it in the file with the needed header and footer.

So you would write to 'log.html', but view 'log.php' which would be:

<html>
  <head>
  </head>
  <body>
    <table>
      <?php include('log.html') ?>
    </table>
  </body>
</html>

Of course, perhaps a better way would be to store the log data without html (in a flat file or database) then generate the view on demand. But for what you're looking for, the above should work.

If it all must be in a static file, you could use

bool ftruncate ( resource $handle , int $size )

to remove the last line of the file. Just make sure you know how long the 'footer' is. Here's some example code that might work for you.

$footer = "</table></html>";
$file = fopen($log_file, 'rw');
ftruncate($file, strlen($footer));
fseek($file, 0, SEEK_END);
fputs($file, $log);
fputs($file, $footer);
fclose($file);

Here's the ftruncate function documentation.

OTHER TIPS

I'm not really sure what you are asking for, but is it something like this?

<table>
    <tr><td> .... </td></tr>
    <?php
        foreach ($logitems as $item)
        {
            echo "<tr><td>" . $value . "</td></tr>\n";
        }
    ?>
</table>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top