简体   繁体   English

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

[英]Read CSV into HTML table - ignore specific columns

I have code that opens a CSV file and loops through every row of data and creates a table from it. 我有打开CSV文件并遍历数据的每一行并从中创建表的代码。

There are specific columns I'd like to ignore. 我想忽略一些特定的列。 How do I change my code to not display certain columns? 如何更改代码以不显示某些列?

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

If you base on the indexes of the column, you could do something like that for example : 如果基于列的索引,则可以执行以下操作:

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

If your CSV file is big, the in_array() function can slow things down a lot. 如果您的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>";

If you want it to work the other way around use: 如果您希望它以其他方式使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM