将CSV读入HTML表 - 忽略特定列

时间:2016-09-02 09:10:15

标签: php

我有代码打开CSV文件并循环遍历每一行数据并从中创建一个表。

我想忽略一些具体的专栏。如何更改代码以不显示某些列?

    <?php
    echo "<table>\n\n";
    $f = fopen("users.csv", "r");
    while (($line = fgetcsv($f)) !== false) {
            echo "<tr>";
            foreach ($line as $cell) {
                    echo "<td>" . htmlspecialchars($cell) . "</td>";
            }
            echo "</tr>\n";
    }
    fclose($f);
    echo "\n</table>";

2 个答案:

答案 0 :(得分:2)

如果您基于列的索引,您可以执行类似的操作,例如:

<?php
    echo "<table>\n\n";
    $f = fopen("users.csv", "r");
    $idsColumnsNotWanted = array(3,4,20);  //indexes of columns you don't want to display
    while (($line = fgetcsv($f)) !== false) {
            echo "<tr>";
            $numcolumn=0;
            foreach ($line as $cell) {
                if(!in_array($numcolumn,$idsColumnsNotWanted)
                    echo "<td>" . htmlspecialchars($cell) . "</td>";
                $numcolumn++;
            }
            echo "</tr>\n";
    }
    fclose($f);
    echo "\n</table>";

答案 1 :(得分:0)

如果你的CSV文件太大,in_array()功能可能会减慢很多事情。

<?php
$exclude = array(3 => 3, 4 => 4, 20 => 20);
echo "<table>\n\n";
$f = fopen("users.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $index => $cell) {
           if ( ! isset($exclude[ $index ]) )
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table>";

如果您希望它以相反的方式使用:

<?php
$include = array(3 => 3, 4 => 4, 20 => 20);
echo "<table>\n\n";
$f = fopen("users.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $index => $cell) {
           if ( isset($include[ $index ]) )
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table>";