从PHP中的文本文件创建一个html表


Creating a html table from a text file in PHP

我正试图从存储在文本文件中的名称列表中创建一个5列html表,这些名称以逗号分隔。

我已经走了这么远,但我还远远不是一个称职的程序员,需要一些帮助。目前,它将表格显示在一个长列中。

<?php
$f = fopen("names.txt", "r");
while (!feof($f)) { 
$arrM = explode(",",fgets($f));   
$val = current  ( $arrM )  ;
print "<table border=1>";
while ( $val )
    {
      print "<tr> <td> $val </td> ";
      $val = next ( $arrM) ;
      print "<td> $val </td> </tr> ";
      print "'n";
      $val = next ( $arrM );
    }
print "</table>";
}
    ?>

提前非常感谢

已解决。。。以下是任何寻求相同帮助的谷歌用户的代码。。

<?php 
    $tdcount = 1; $numtd = 3; // number of cells per row 
    print "<table>"; 
    $f = fopen("names.txt", "r"); 
    while (!feof($f)) { 
        $arrM = explode(",",fgets($f)); 
        $row = current ( $arrM ); 
        if ($tdcount == 1) 
            print "<tr>"; print "<td>$row </td>"; 
        if ($tdcount == $numtd) { 
            print "</tr>"; 
            $tdcount = 1; 
        } else { 
            $tdcount++; 
        } 
    } 
    if ($tdcount!= 1) { 
        while ($tdcount <= $numtd) { 
            print "<td>&nbsp;</td>"; $tdcount++; 
        } print "</tr>"; 
    } 
    print "</table>"; 
?>

使用fgetcsv():将CSV文件打印为HTML表,无论它有多少列

if( ($handle = fopen( 'test.csv', 'r' )) !== false )
{
    $output = '<table>';
    while( ($data = fgetcsv( $handle )) !== false )
    {
        $output .= '<tr>';
        foreach( $data as $value )
        {
            $output .= sprintf( '<td>%s</td>', $value );
        }
        $output .= '</tr>';
    }
    fclose( $handle );
    $output .= '</table>';
}
echo $output;

如果$arrM包含一个从对逗号分隔的数据字符串执行的explode()派生的数组,那么您所要做的就是在$arrM 上执行foreach()

echo "<table border='1'>";
foreach ($arrM as $val) {
    echo "<tr><td>" . $val . "</td></tr>";
}
echo "</table>";

当然,如果您想创建一个包含一列和多行的垂直表,则需要这样做。然而,如果这是你想要实现的,那么它听起来更像是一个列表,而不是一个表格。在这种情况下,你可以试试这个:

echo "<ul>";
foreach ($arrM as $val) {
    echo "<li>" . $val . "</li>";
}
echo "</ul>";

然后您可以使用CSS(级联样式表)对其进行样式设置。

UPDATE:如果您想在列中显示所有名称,只需将<tr>标记分开即可:

echo "<table border='1'><tr>";
foreach($arrM as $val) {
    echo "<td>" . $val . "</td>";
}
echo "</tr></table>";

如果你只想要x列,还有一种方法可以做到:

$maxCols = 10;
$counter = 0;
echo "<table border='1'>";
foreach ($arrM as $val) {
    $newRow = ($counter++ % $maxCols == 0);
    if ($newRow) {
        echo "<tr>";
    }
    echo "<td>" . $val . "</td>";
    if ($newRow) {
        echo "</tr>";
    }
}
// fill out the rest of the table
$remainingCols = $maxCols - (count($arrM) % $maxCols);
for ($i = 0; $i < $remainingCols; $i++) {
    echo "<td>&nbsp;</td>";
}
echo "</table>";

我的数学可能不太好,但你至少应该能够使用并调试这段代码。