Linux file and table output

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Caziques
Forum Newbie
Posts: 1
Joined: Fri Apr 18, 2008 2:08 am

Linux file and table output

Post 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>");
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Linux file and table output

Post 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>
Post Reply