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.
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
<div>
block as the buffer</div><div>
to replace any blank line (else copy the line read to the buffer)</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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.