5

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

7 Answers 7

7

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>
Sign up to request clarification or add additional context in comments.

1 Comment

@cjd143SD, it should work perfectly now. It takes the presence of "PREFIX=" etc. into account and should work for any number of rows and columns.
6

This should be flexible enough and won't require any hard-coded pair names:

<?php

$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));

foreach($lines as $i => $line) {
    $pairs = explode(';', $line);
    foreach($pairs as $pair) {
        list($column, $value) = explode('=', $pair, 2);
        $columns[$column] = true;
        $rows[$i][$column] = $value;
    }
}

$columns = array_keys($columns);


echo '<table><thead><tr>';

foreach($columns as $column) {
    echo '<th>'.$column.'</th>';
}

echo '</tr></thead><tbody>';

foreach($rows as $row) {
    echo '<tr>';
    foreach($columns as $column) {
        echo '<td>'.$row[$column].'</td>';
    }
    echo '</tr>';
}
echo '</tbody></table>';

?>

2 Comments

thanks. works great. good example of using preg_split. new for me. ;-)
No problem. file() can take care of empty lines, too, but using this method has the added benefit of trimming whitespace.
0
echo '<table><tr><td>PREFIX</td><td>Part</td>File</td></tr>';
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   $count=count($pieces);

   echo '<tr>';
   for ($counter=0; $counter <$count; $counter++)
   {
     echo '<td>'.$pieces[$counter].'<td>';
   } 
  echo '</tr>';
}

Comments

0

Not the prettiest solution, just an example:

echo '<table><tr><td>PREFIX</td><td>PART</td><td>FILE</td></tr>';
foreach ($Inputfile as $line)
{
    $pieces = explode(';', $line);
    echo sprintf(
        '<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
        ltrim($pieces[0], 'PREFIX='),
        ltrim($pieces[1], 'PART='),
        ltrim($pieces[2], 'FILE=')
    );
}
echo '</table>';

Comments

0

You've really got two problems here:

1) Parsing the information in each line into a record / associative array

2) Representing the series of these records/arrays as an HTML table.

Good code will separate these concerns somewhat.

function line2record($line) {
   $recordAA = array();
   $keyValuePairs = explode(';',$line);
   foreach($keyValuePairs as $kvp) {
       $pieces = explode('=',$kvp);
       $recordAA[$pieces[0]] = $pieces[1];
   }
   return $recordAA;
}

function record2TR($recordAA) {
   $str = implode('</td><td>',$recordAA);
   return "<tr><td>$str</td></tr>";
}

After that, it's pretty much a matter of applying these two functions to each line of the file:

$Inputfile = file("prod.txt");
foreach ($Inputfile as $line)
    echo record2TR(line2record($line));

To get the header row, and the table/open close markup, you might do something like this:

function record2TH($recordAA) {
    $headers = array_keys($recordAA);
    $str = implode('</th><th>',$headers);
    return "<tr><th>$str</th></tr>";
}

and then:

$fp = fopen('prod.txt','r');
$line = fgets($fp,MAX_LINE_LENGTH);  // you'd set this constant
$firstRecord = line2record($line);
echo "<table>";
echo record2TH($firstRecord);
echo record2TR($firstRecord);
while($line = fgets($fp,MAX_LINE_LENGTH))
    echo record2TR(line2record($line));
echo "</table>";

Comments

0

This was my approach

echo '<table id="time-table" border="2"><thead><tr >';
echo '<th style="width:40%; padding: 7px;">Course Code</th>';
echo '<th style="width:30%">Course Name</th>';
echo '<th style="width:40%">Slot</th>';
for ($x = 0; $x < 5; $x++) {
   echo '<tr id=row'.$x.'>';
   echo '<th style="width:40%; padding: 15px;" >',$xml_data->children()[$x]->coursecode .'</th>';
   echo '<th style="width:30%">',$xml_data->children()[$x]->coursename .'</th>';
   echo '<th style="width:20%">',$xml_data->children()[$x]->slot .'</th>';
 }
echo '</tbody></table>';

Comments

0
<?php

class Table {

private $table;
private $rows;

public function __construct()
{

}



function valueof($var, $key, $default_return_value = null, $run_value_in_this_function = '')
{

    $return_value = $default_return_value;

    if (is_object($var)) {
        if (isset($var->$key)) {
            $return_value = trim($var->$key);
        }
    } elseif (is_array($var)) {
        if (isset($var[$key])) {
            $value = $var[$key];
            $return_value = is_string($value) ? trim($value) : $value;
        }
    } else {
        $return_value = $default_return_value;
    }

    if (!empty($return_value) && !empty($run_value_in_this_function)) {
        if (function_exists($run_value_in_this_function)) {
            $return_value = $run_value_in_this_function($return_value);
        }
    }

    return $return_value;
}

function addRow($index)
{

    $this->rows[$index] = [];

    $this->table['rows'][$index] = [];

}

function addRows($rows)
{
    $rows = (int) $rows;
    for ($r = 0; $r <= $rows; ++$r) {

        $this->rows[$r] = [];

        $this->table['rows'][$r] = [];
    }

}

function addCell($row_index, $cell_index, $cell_value)
{
    $this->table['rows'][$row_index][$cell_index] = $cell_value;
}

function updateCell($row_index, $cell_index, $cell_value)
{
    $this->table['rows'][$row_index][$cell_index] = $cell_value;
}

function updateColumn($column_index, $cell_values = [])
{

    if (isset($this->table['rows'])) {
        if (count($this->table['rows']) > 0) {
            foreach ($this->table['rows'] as $row_index => $row_cells) {

                $value_index = $row_index;
                $new_value =  $this->valueof($cell_values, $value_index);

                if (!is_null($new_value)) {
                    $this->updateCell($row_index, $column_index, $new_value);
                }
            }
        }
    }

}

function updateRow($row_index, $row_values = [])
{

    if (isset($this->table['rows'][$row_index])) {

        $columns = count($this->table['rows'][$row_index]);

        foreach ($this->table['rows'][$row_index] as $column_index => $column_value) {

            $value_index = $column_index-1;
            $new_value =  $this->valueof($row_values, $value_index);

            if (!is_null($new_value)) {
                $this->updateCell($row_index, $column_index, $new_value);
            }
        }
    }

}
function addHeader($row_values = [])
{

    if (!empty($row_values)) {
        $this->updateRow(0, $row_values);
    }

}

function addColum($column_index)
{

    if (isset($this->table['rows'])) {
        if (count($this->table['rows']) > 0) {
            foreach ($this->table['rows'] as $row_index => $row_cells) {
                $this->table['rows'][$row_index][$column_index] = null;
            }
        }
    }
}
function addColums($columns)
{

    $columns = (int) $columns;

    for ($col = 1; $col <= $columns; ++$col) {
        if (isset($this->table['rows'])) {
            if (count($this->table['rows']) > 0) {
                foreach ($this->table['rows'] as $row_index => $row_cells) {
                    $this->table['rows'][$row_index][$col] = null;
                }
            }
        }
    }
}

public function getTable()
{


    if (isset($this->table['rows']) && is_countable($this->table['rows'])) {

        $table = "<table border=\"1\" width=\"50%\">";

        foreach ($this->table['rows'] as $row_index => $row_cells) {

            $table .= "<tr>";

            if (is_countable($row_cells)) {
                foreach ($row_cells as $cell_index => $cell_value) {

                    if (empty($cell_value)) {
                        $cell_value = '&nbsp;';
                    }

                    $table .= "<td class=\"data\"> {$cell_value}</td>";

                }
            }

            $table .= "</tr>";

        }

        $table .= "</table>";

    }

    return $table;

}

function makeTable()
{

    $this->addRows(5);
    $this->addColums(4);

    $this->addHeader(['No', 'Name', 'Unit', 'Number']);
    $this->updateColumn(1, [null, '1', '2', '3', '4', '5' ]);
    $this->updateColumn(2, [null, 'Cat', 'Dog', 'Horse', 'Cow', 'Hen']);
    $this->updateColumn(3, [null, 'Each', 'Each', 'Each', 'Each' ]);
    $this->updateColumn(3, [null, 10,20, 5, 50, 45]);

    // echo '<pre>';
    // print_r($this->table);
    // echo '</pre>';

    $table = $this->getTable();

    return $table;


}

}

$table = new Table();

print $table->makeTable();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.