PHP Trick: fputcsv and fgetcsv

We’ve all come across the time where we’ve needed to pull data from a database and dump it to a CSV file for backup or reporting purposes. There are many challenges in doing so: escaping commas, escaping double strings, adding newlines, etc… It seems like I solve this problem many times on my own by using a different delimeter such as a semicolon or tab. However, after using Excel on a Mac for awhile, I began to realize that using an alternate delimeter for a csv file requires a few extra steps to make the data display correctly in Excel.

Then I came across two PHP functions:  fputcsv and fgetcsv.

fputcsv will store an array of strings to a file and automatically handle any additional escaping and newlines.
fgetcsv will do the opposite and GET an array of strings from one line of a csv file.

In my case, I only wanted to output a string to the browser with an attachment header so that it would prompt a download of a csv file. I actually learned a new trick as well:

I can fake a file-pointer by specifying a file location of php://output.

Here is the final output: