1

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

2 Answers 2

1

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>";
Sign up to request clarification or add additional context in comments.

Comments

1

One possible solution would be to change your code to:

$idsColumnsWanted = array(0,1,19,16);
for($i=0;$i<count($line);$i++) {
    if (in_array($i, $idsColumnsWanted)) {
        if ($cell !== '') {
            $row .= "<".$col.">" . htmlspecialchars($cell) . "</".$col.">";
        } else {
            $is_empty = true;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.