michaelmcgurk michaelmcgurk - 3 months ago 5
HTML Question

Hide certain table columns from CSV with PHP

I am generating an HTML table from a CSV file using the following code.

I'd like to only display columns with the following indexes:

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


How do I work this into my existing code?

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

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

$first_line=false;

while (($line = fgetcsv($f)) !== false) {
$row ="";

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


$is_empty = false;

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


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

Answer

You can try with in_array() function, and adding an index $i to your cycle:

$idsColumnsWanted = array(0,1,19,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>";