简体   繁体   中英

How to read multiple lines from a file until a blank line in PHP?

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.

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

  1. start with a <div> block as the buffer
  2. Loop over the log file and use </div><div> to replace any blank line (else copy the line read to the buffer)
  3. 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:

http://www.createchhk.com/SOanswers/logs2.txt

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM