Last updated on February 24, 2015
In this post i will show you how to read CSV file with PHP. CSV is a type of file. It means Comma Separated Values.
By using PHP’s fgetcsv() function we will work with CSV Files.this function parses a line from an open file, checking for CSV fields. and it will return the CSV fields in an array on success, or FALSE on failure.
Here is the Example :
function csvToArray($file){ $rows = array(); $cols = array(); if(file_exists($file) && is_readable($file)){ $handle = fopen($file, 'r'); while (!feof($handle) ) { $row = fgetcsv($handle, 10240); if(empty($cols)) $cols = $row; else if(is_array($row)) $rows[] = array_combine($cols, $row); } fclose($handle); } else { throw new Exception($file.' doesn`t exist or is not readable.'); } return $rows; }
That’s it.