Working With CSV Files in PHP
Working with CSV files sucks. You have to handle different line endings and entries can be wrapped in double quotess which could have a comma inside of it preventing you from just using explode()
. Thankfully, PHP provides two functions for working with CSV files that are super helpful.
fgetcsv
The first is fgetcsv
which reads from a file handle and brings in single line broken into an array. If you've every worked with processing csv files before you know how awesome this is. As an example,
fputcsv
The other is fputcsv
which writes to a file with the correct formatting for a CSV file:
Output to the Browser
Occasionally, we want to create a CSV file for a user to download. We could save the file to disk and then redirect to the output but I would rather just output the results:
Converting a CSV File Into an Associative Array
Using fgetcsv
we can convert a CSV file into an associative array. I like this approach because then it doesn't mater what order the columns are in the CSV.
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows