PHP – Read CSV File into an Array
A Comma-separated values (CSV) file stores tabular data in plain-text form. It is often a record separated by a comma or other delimiter. In this tutorial, we are going to see how to read a CSV file into an Array with PHP.
Example of a CSV file:
Yohan, USA, 32 years old Jean, United Kingdom, 25 years old Alex, France, 22 years old Emily, USA, 18 years old
The first column is the person’s name, the second column is the person’s country and the last column is the age. As you can see, each person is separated by a new line.
[st_adsense]
In PHP, there is a function called fgetcsv, which will automatically parse the CSV fields of a given resource descriptor.
Here is a simple function that shows how to read our CSV file and returns a multidimensional array containing the CSV data.
<?PHP function read($csv){ $file = fopen($csv, 'r'); while (!feof($file) ) { $line[] = fgetcsv($file, 1024); } fclose($file); return $line; } // Define the path to CSV file $csv = 'myfile.csv'; $csv = read($csv); echo '<pre>'; print_r($csv); echo '</pre>'; ?>
Output:
Array ( [0] => Array ( [0] => Name [1] => Country [2] => Age ) [1] => Array ( [0] => Alex [1] => France [2] => 22 years old ) [2] => Array ( [0] => Emily [1] => USA [2] => 18 years old ) [3] => Array ( [0] => Jean [1] => United Kingdom [2] => 25 years old ) [4] => Array ( [0] => Yohan [1] => USA [2] => 32 years old ) )[st_adsense]
Where did the array titles come from? The filed names of Name, Country, and Age don’t seem to be defined anywhere, but show up in the printout of array 0.
The array titles come from the CSV file.