How to extract data from csv file in PHP
In this post we will show you how to convert csv(Comma separated values) to array. to convert scv to array or get data form csv file we use fgetcsv. by using this function we can convert csv to array.
we use fgetcsv for get dat form csv file to array in php.
Description of fgetcsv() function :
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = “,” [, string $enclosure = ‘”‘ [, string $escape = “\” ]]]] ) // fgetcsv function
Parameters of fgetcsv() =>
handle : A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen() function.
length : Must be greater than the longest line (in characters length) to be found in the CSV file (allowing for trailing line-end of characters). Otherwise the line is split in chunks of length characters, unless the split would occur inside an enclosure. Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later version) the maximum line length is not limited, which is slightly slower.
delimiter : The optional delimiter parameter is sets for the field delimiter (allow one character only).
enclosure : The optional enclosure parameter is sets for the field enclosure character (allow one character only).
escape : The optional escape parameter is sets for the escape character (allow one character only).
fgetcsv() — Gets line from file pointer and analyze for CSV fields.
Similar to fgets() except that fgetcsv() parses the road it browses for fields in CSV format associate degreed returns an array containing the fields read.
Method – 1
$count_row = 0; $csv_file = fopen("contacts.csv","r"); while(($get_data = fgetcsv($csv_file, 1000, ",")) !== FALSE) { $count_row++; $countNum = count($get_data); echo "$countNum fields in line $count_row:\n"; $csv_data[$count_row] = $get_data; } fclose($csv_file); echo "<pre>"; // print all data of csv file. print_r($csv_data); echo "</pre>";
Method – 2
function csv_to_array($csv_file){ $file_handle = fopen($csv_file, 'r'); while (!feof($file_handle) ) { $line_of_text[] = fgetcsv($file_handle, 1005); } fclose($file_handle); return $line_of_text; } // Set path to CSV file $csv_file = 'contacts.csv'; $csv_array = csv_to_array($csv_file); echo '<pre>'; print_r($csv_array); echo '</pre>';