如何在PHP中创建HTML表格

5
我有以下代码片段,基本上使用explode函数将这些值拆分出来:
<?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);
}
?>

数据:(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

有人可以向我展示如何动态地将这个放入HTML表格中,就像这样?有没有简单的方法来做到这一点?谢谢。
PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2
7个回答

7

简洁的方法

<?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>

@cjd143SD,现在应该完美运行了。它考虑到了“PREFIX=”等的存在,并且适用于任意数量的行和列。 - Geoffrey

6

这应该足够灵活,不需要任何硬编码的配对名称:

<?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>';

?>

谢谢。运行得很好。使用 preg_split 的好例子。这对我来说是新的。;-) - cjd143SD
没问题。file() 也可以处理空行,但使用这种方法的好处是可以修剪空格。 - Kevin

0

这是我的方法

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>';

0
<?php

类 表格 {

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();

$table = 新的Table();

print $table->makeTable();


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>';
}

0

这不是最美观的解决方案,只是一个例子:

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>';

0

你真的有两个问题:

1)将每行中的信息解析为记录/关联数组

2)将这些记录/数组系列表示为HTML表格。

好的代码会在一定程度上分离这些问题。

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>";
}

之后,就是将这两个函数应用到文件的每一行了:

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

要获取表头行和表格/打开关闭标记,您可以执行以下操作:

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

然后:

$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>";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接