Search code examples
phpfgetcsv

PHP fgetcsv - Skip columns?


I am trying to import a CSV, and be able to remove columns, and only import the ones selected.

So I have an array of selected fields, and the CSV file. I can remove rows, but having problems skipping columns.

Here is what i'm using to display a table, just trying to test out removing the column. Nothing fancy here. Just need to know where to place any if statements, or anything. Tips, suggestions, samples all welcome!

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        echo("<tr>\r\n");
                        foreach ($data as $index=>$val) {
                        echo("\t<td>$val</td>\r\n");
                        } 
                        echo("</tr>\r\n");
               } //end while

Where do i place any if statement to allow only the remainder of rows? i've tried in_array, array_diff, etc - and nothing seems to be working?

Now that i'm typing this out, should I just use PHP to delete the columns before insert? What would be best practice?

thanks jt


Solution

  • You can set an array containing the columns to display (in my ex 1 and 3) and use the key part of the foreach to know which is the column you are scanning:

    <?
    $handle = fopen("test.csv", "r");
    
    $columns = array(1,3);
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            echo("<tr>\r\n");
            foreach ($data as $index=>$val) {
                    if (in_array($index+1, $columns)) {
                            echo("\t<td>$val</td>\r\n");
                    }
            }
            echo("</tr>\r\n");
    } //end while
    
    ?>