Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create html table in php

I have the following snippet of code that basically uses explode to split out these values:

<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>

Data: (prod.txt)

PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2
like image 824
cjd143SD Avatar asked Dec 22 '22 20:12

cjd143SD


1 Answers

The Clean Way

<?php
$inputfile = file("prod.txt");

$data_lines = array();
foreach ($inputfile as $line)
{
    $data_lines[] = explode(";", $line);
}

//Get column headers.
$first_line = array();
foreach ($data_lines[0] as $dl)
{
    $first_line[] = explode("=", $dl);
}
$headers = array();
foreach ($first_line as $fl)
{
    $headers[] = $fl[0];
}

// Get row content.
$data_cells = array();
for ($i = 0; $i < count($data_lines); $i++)
{
    $data_cell = array();
    for ($j = 0; $j < count($headers); $j++)
    {
        $data_cell[$j] = substr($data_lines[$i][$j], strpos($data_lines[$i][$j], "=")+1);
    }
    $data_cells[$i] = $data_cell;
    unset($data_cell);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>HTML Table With PHP</title>
    </head>
    <body>
        <table border="1">
            <tr>
            <?php foreach ($headers as $header): ?>
                <th><?php echo $header; ?></th>
            <?php endforeach; ?>
            </tr>
        <?php foreach ($data_cells as $data_cell): ?>
            <tr>
            <?php for ($k = 0; $k < count($headers); $k++): ?>
                <td><?php echo $data_cell[$k]; ?></td>
            <?php endfor; ?>
            </tr>
        <?php endforeach; ?>
        </table>
    </body>
</html>
like image 161
Geoffrey Avatar answered Jan 02 '23 07:01

Geoffrey