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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.