Search code examples
phphtmlreadfile

Extract certain data from a text file and create a table


Hi I am very new on PHP programming i am just trying to learn a little bit more on how can i work with files.

I having a text file with some bunch of data like below.

image from the file

Policy Name:       TU_TOPS_VM-Full_30D_00_2
  Daily Windows:
         Saturday   19:50:00  -->  Sunday     06:00:00
Policy Name:       TU_QW_VM-FULL_30D_18_01
    Daily Windows:
          Sunday 02:05:00 --> Sunday 09:00:00
Policy Name:       TU_GPAS_FULL-VM_30D_18_01
    Daily Windows:
          Friday     22:00:00  -->  Saturday   06:00:00

I would like to have an output similar to this in a table.

POlicy                               Day              Time
TU_TOPS_VM-Full_30D_00_2 Saturday    Saturday         19:50:00
TU_QW_VM-FULL_30D_18_01              Sunday           02:05:00
TU_GPAS_FULL-VM_30D_18_01            Friday           22:00:00

From my code i was able to obtain the Policy name and organize the data in a table column.

Output from code.

POlicy                        Day     Time
TU_TOPS_VM-Full_30D_00_2
TU_QW_VM-FULL_30D_18_01

What i was able to do so far.

<?php
$lines= file('schedule');
$lines = preg_grep("/Policy Name:/", $lines);
echo'
<table>
<tr>
<td>POlicy</td>
<td>Day</td>
<td>Time</td>
</tr>';
foreach ($lines as $policy) {
$find="Policy Name:";
$replace="";
$po= (str_replace($find,$replace,$policy));
echo '
<tr>
<td>'.$po.'<br></td>
</tr>
</table>';
}
?>

How can i extract the day and time and organize it beside the policy name?.


Solution

  • You're throwing away the other lines when you use preg_grep. Instead, loop over all the lines, checking which kind of line it is.

    Also, </table> should not be inside the loop, it should only be at the end of the loop.

    <?php
    $lines= file('schedule', FILE_IGNORE_NEW_LINE);
    echo'
    <table>
    <tr>
    <td>POlicy</td>
    <td>Day</td>
    <td>Time</td>
    </tr>';
    foreach ($lines as $line) {
        if (strstr($line, 'Policy Name:')) {
            $policy = str_replace('Policy Name:', '', $line);
        } elseif (preg_match('/(\w+)\s+(\d\d:\d\d:\d\d)\s+-->/', $line, $match)) {
            $day = $match[1];
            $time = $match[2];
        echo "
    <tr>
    <td>$policy</td>
    <td>$day</td>
    <td>$time</td>
    </tr>";
        }
    }
    echo "\n</table>";
    ?>