从CSV生成HTML表 - 忽略不需要的列

时间:2016-09-05 08:03:27

标签: php

我有这个代码,它采用CSV并从中生成HTML表格。

我有array名为$idsColumnsWanted,我打算只存储我想在表格中显示数据的列。

不幸的是,它目前的工作方式,在第0列和第0列之后显示1,它不显示任何其他内容。之后它忽略了一切。

我做错了什么?

<?php

$idsColumnsWanted = array(0,1,16);

echo "<table class='table table-bordered'>\n\n";

$f = fopen("users.csv", "r");

$first_line=false;

while (($line = fgetcsv($f)) !== false) {

    // Restart column index
    $i = 0;

    $row ="";

    if($first_line == false) {
         $row = "<thead><tr>";
         $col= "th";
    }
    else {
         $row = "<tr>";
         $col= "td";
    }


    $is_empty = false;

    foreach ($line as $cell) {

        // Skips all columns not in your list
        if (! in_array($i, $idsColumnsWanted)) continue;

        if ($cell !== '') {
            $row .= "<".$col.">" . htmlspecialchars($cell) . "   </".$col.">";
        } else {
            $is_empty = true;
        }

        // Increase index
        $i++;

    }


    if($first_line == false) $row .= "</tr></thead>";
    else $row .= "</tr>";

    $first_line=true;

    if ($is_empty) {
        continue;
    } else {
        echo $row;
    }

}
fclose($f);
echo "\n</table>";

?>

1 个答案:

答案 0 :(得分:1)

也许,你可以这样做:

    <?php

        $idsColumnsWanted   = array(0,1,16);
        $output             = "<table class='table table-bordered'>\n\n";
        $f                  = fopen("file.csv", "r");
        $csv                = fgetcsv($f);
        $counter            = 0;

        while (($line = fgetcsv($f)) !== false){
            if($counter == 0){
                // BUILD THE TABLE HEADER
                $output    .= "<thead>\n<tr>" . PHP_EOL;
                foreach($line as $i=>$cell){
                    // SKIP UNWANTED COLUMNS...
                    if (!in_array($i, $idsColumnsWanted)) continue;
                    if(!empty($cell)) {
                        $output .= "<th>{$cell}</th>" . PHP_EOL;
                    }
                }
                // CLOSE THE TABLE HEADER & ITS ROW
                $output    .= "</tr>\n<thead>" . PHP_EOL;
                // ADD THE TABLE BODY TAG
                $output    .= "</tbody>" . PHP_EOL;
            }else{
                // BUILD THE NORMAL TABLE-ROWS
                $output .= "<tr>" . PHP_EOL;
                foreach($line as $i=>$cell){
                    // SKIP UNWANTED COLUMNS...
                    if (!in_array($i, $idsColumnsWanted)) continue;
                    if(!empty($cell)){
                        $output .= "<td>" . htmlspecialchars($cell) . "</td>" . PHP_EOL;
                    }
                }
                $output .= "</tr>" . PHP_EOL;
            }
            $counter++;
        }
        // CLOSE THE TABLE BODY AND THE TABLE ITSELF.
        $output    .= "</tbody>" . PHP_EOL;
        $output    .= "</table>" . PHP_EOL;

        fclose($f);

        // ECHO THE OUTPUT...
        echo $output;
    ?>