guh.me - gustavo's personal blog

Generating and downloading CSV files in PHP

βΈ»

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{:target="_blank"}. Among these packages, we have a great selection from The League of Extraordinary Packages{:target="_blank"}, which includes a great CSV library{:target="_blank"} called League\CSV.

You can get this library through Composer:

$ composer require league/csv

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.

<?php

use League\Csv\Writer;

$csv = Writer::createFromFileObject(new SplTempFileObject());
$csv->insertOne(['#', 'Date', 'Customer', 'Email']);

foreach ($orders as $order)
{
  $csv->insertOne($order->id, $order->created_at, $order->name, $order->email);
}

$csv->output('orders.csv');
exit;

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{:target="_blank"}.