It has been a long time since I have needed to generate a CSV file in PHP. At that time, it involved creating huge strings and manually separating columns with semicolons and adding line breaks to each line (or using fopen, fputcsv, which is as bad). To make it downloadable, it also involved setting a few headers manually.

PHP is experiencing a renaissance, and that means we now have a plethora of high-quality packages - just take a look at Packagist. Among these packages, we have a great selection from The League of Extraordinary Packages, which includes a great CSV library called League\CSV.

You can get this library through Composer:

In the example below, I instantiated the Writer class and I used the in-memory adapter to create the CSV file (you can use other adapters if you want to persist the file). I added labels to the first row, and then I added the data rows. To make the file downloadable, I just called the Writer::output method and exited the script. All the required headers are set automagically by the output method.

Pretty effective and concise.

The library has many other features, covering many different use cases. You can read more about it on their official website at http://csv.thephpleague.com.