How to convert a CSV file into an array with PHP

Loading CSV files into an array is something that comes up more times than I’d like to admit. Scrubbing mailing lists, loading flat files to a database and various other use cases are out there and fortunately, PHP makes it easy to to do. There are a few ways to load files but the preferred method when you are uncertain what the format of the file will be would be to open a file pointer and use fgetcsv() to grab each line. The reason for this is because CSV fields can have line breaks in them which would make explode() bork the data.

$csv = array

if (($file = fopen('test.csv', 'r')) === false)
{
	throw new Exception('There was an error loading the CSV file.'
}
else
{
	while (($line = fgetcsv($file, 1000)) !== false)
	{
		$csv[] = $line
	}

	fclose($handle
}

The 1000 passed to fgetcsv() is to indicate how many bytes you want to load of the line. 1000 is usually enough, but you can adjust to the expected size of your file’s lines. The other option is to omit the value all together (as of PHP 5.0 and above) but that will result in slower execution.

Now let’s say you know the CSV file you are loading is never going to have line breaks in the values and you’re using PHP 5.3 of above. In that scenario, you could skip opening the file pointer and simply your code a bit:

$csv = explode("n", file_get_contents('test.csv'

foreach ($csv as $key => $line)
{
	$csv[$key] = str_getcsv($line
}

There you have it, how to load a CSV file and convert it into an array!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.