skip columns of csv file in php

skip columns of csv file in php

In this post we will show you how to skip columns of csv file using fgetcsv function in php. hear we give you two differ method for skip columns of csv file in php.

skip columns of csv file in php
skip columns of csv file in php

Method – 1

This method is short and seet to skip columns in csv file using array_intersect_key. by using this code we can skip any columns of csv file. in this code we skip 1,4,14 columns, but fgetcsv start index with 0 so we pass columns number - 1. so if you have to skip any row then subtraction with 1. pass your columns number in $skip_columns_data .

Note : If you don’t have to store the column numbers as keys in your result of array then use array_values(array_intersect_key(…)).

// open csv file  
$csv_file = fopen("contacts.csv","r");
$csv_data = [];

// pass your skipping columns number
$skip_columns_data = array_flip([0, 5, 15]);

while (false !== $csv_fields = fgetcsv($csv_file)) 
{
    $csv_data[] = array_intersect_key($csv_fields, $skip_columns_data);
}

// close csv file 
fclose($csv_file);

// print csv data 
// csv data is in array
echo "<pre>";
print_r($csv_data);
echo "</pre>";

Method – 2

In this method we skip column number using for loop, in this method we pass over skipping columns number in $skip_columns_data . By using for loop we check column number if it will same in array then skip it. This code we skip 1,4,14 columns, but fgetcsv start index with 0 so we pass columns number - 1. so if you have to skip any row then subtraction with 1.

// count row number
$row = 1;

// open csv file  
$csv_file = fopen("contacts.csv","r");

// pass your skipping columns number
$skip_columns_data = array(0, 5, 15);
while (($data = fgetcsv($csv_file, 1000, ",")) !== FALSE) {

		// cout row number of csv
        $row_num = count($data);
		
		// increase row counter 	
        $row++;
		
		// print row number and total filed of csv
		echo "<p> $row_num fields in line $row: <br /></p>\n";
		
        for ($counts=0; $counts < $row_num; $counts++) 
		{
			 // check row for skip columns 				
            if (in_array($counts, $skip_columns_data))
            {
                // Match found in csv 
				// skip columns of csv
				continue;
            }
            else
            {				
				// print data of columns
                echo $data[$counts] . "<br />\n";
				// add data of columns on array
                $csv_data[$row][] = $data[$counts];
            }
        }
   }
   
// close csv file 
fclose($csv_file);

echo "<pre>";
print_r($csv_data);
echo "</pre>";

Leave a Comment

Your email address will not be published. Required fields are marked *

64  +    =  66

We accept paid advance and paid guest Posting on our Site : Contact US