0

I have code that opens a CSV file and loops through every row of data and creates a table from it.

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>";
2
  • 2
    Do you know the indexes of the columns you wish to ignore or just basing it on the value? Commented Sep 2, 2016 at 9:12
  • Yes, I know the indexes. 3,4,20. Commented Sep 2, 2016 at 9:14

2 Answers 2

2

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

2 Comments

Don't forget to put the indexes of column you actually don't want to display.
Perfection :-D I've actually changed this so it displays the columns I do want. Less typing as we're hiding loads. Thank you so much sir :)
0

If your CSV file is big, the in_array() function can slow things down a lot.

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

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.