I am working with a log file that contains many lines. I want to use this log file in my dashboard. The file is in this format:
line1
line2
line3
line4
line5
line6
line7
line8
I want to read this file, and show its contents such as:
line1 line2 line3
line4 line5
line6 line7 line8
How can I do this in php?
Note: I can read the file and echo results in my dashboard. I just need the above function.
So far:
<php?>
$logs = File::get('logs.txt');
$lines=explode("\n", $logs);
echo $lines['0'];
but this shows me only the first line.
CodePudding user response:
METHOD ONE
Assuming that you use $xline as a temp buffer.
Looping over the log file , read one line at a time. (say use fgets)
Then concat the data read from the log to the temp buffer if the line read from the log is not blank, otherwise display the buffer, clear it and and read the fresh line into the buffer
So the code is:
<?php
$xline="";
$handle = fopen("./logs.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (trim($line)!=""){
$xline.= " " . trim($line);
}else{
echo $xline."<br>";
$xline=$line;
}
}
}
echo $xline."<br>";
?>
Fully working example:
http://www.createchhk.com/SOanswers/SOanswer11Sep2022.php
Log file:
http://www.createchhk.com/SOanswers/logs.txt
METHOD TWO
- start with a
<div>
block as the buffer - Loop over the log file and use
</div><div>
to replace any blank line (else copy the line read to the buffer) - After the file is read , output the buffer and a
</div>
So the code will be
<?php
$xline="<div>";
$handle = fopen("./logs2.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (trim($line)!=""){
$xline.=$line;
}else{
$xline.="</div><div>";
}
}
}
echo $xline ."</div>";
?>
Fully working example:
http://www.createchhk.com/SOanswers/SOanswer11Sep2022b.php
Log file: