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.
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:
There you have it, how to load a CSV file and convert it into an array!