Page 1 of 1

Linux file and table output

Posted: Fri Apr 18, 2008 2:15 am
by Caziques
Please HELP

I am sure this is pritty simple but I need some assistance.
I have a php script that reads a file from linux with lines of text in as follows

Code: Select all

1.24.64.1       0.0.0.0     255.255.255.255  dsl2
0.0.0.0          0.0.0.0     0.0.0.0               dsl2
I would like to take this info and print the details into a table but i dont seem to be able to get it right. it prints rows but doesnt split the data into coloms
Here is a exampel of my code :

Code: Select all

$readfile = file("/tmp/test3");
for ($k=0; $k<=count($readfile)-1; $k++) {
    $fields = split("\t",$readfile[$k]);
    print(" $fields[0] <br>");

Re: Linux file and table output

Posted: Fri Apr 18, 2008 8:48 am
by Chris Corbyn
I'd do it in two stages; first turning the data into a 2d array (like a table), then using that to output the data. I know people will say this is doing things twice but it's best to separate your business logic from your presentation logic.

Code: Select all

$tableData = array();
 
foreach (file($theFile) as $line) {
  $tableData []= preg_split('/\s+/', trim($line));
}
Then:

Code: Select all

<table>
<?php foreach ($tableData as $row): ?>
  <tr>
  <?php foreach ($row as $value): ?>
    <td><?php echo $value; ?></td>
  <?php endforeach; ?>
  </tr>
<?php endforeach; ?>
</table>