Export data to CSV file on Symfony

In this post, I will guide you to export data to csv file on Symfony. It's simple way to use StreamedResponse. It will generate an file csv allow you download when you access to routing.

Routing

I always use yml to define the routing, you can use xml or annotations if desired
#src/Acme/CommonBundle/Resource/config/routing.yml
acme_common_export_csv:
  path:     /export/csv
  defaults: { _controller: AcmeCommonBundle:Common:exportCSV }
This routing use exportCSVAction method in Common Controller Class

Controller

In exportCSVAction method, you can perform the following steps:
- load data (with conditions)
- new response = StreamedResponse Class & put data (array fields you has load) to csv use fputcsv - return response with attachment file name
namespace AcmeCommonBundleController;

use DoctrineORMEntityManager;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationStreamedResponse;

class CommonController extends Controller
{
    public function exportCSVAction()
    {
        $results = $this->getDoctrine()->getManager()
            ->getRepository('AcmeUserBundle:User')->findAll();

        $response = new StreamedResponse();
        $response->setCallback(
            function () use ($results) {
                $handle = fopen('php://output', 'r+');
                foreach ($results as $row) {
                    //array list fields you need to export
                    $data = array(
                        $row->getId(),
                        $row->getName(),
                    );
                    fputcsv($handle, $data);
                }
                fclose($handle);
            }
        );
        $response->headers->set('Content-Type', 'application/force-download');
        $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');

        return $response;
    }

Then, when you access http://example.local/export/csv you will get CSV data file. This attachment file name is export.csv
You can change format on CSV file by argument in fputcsv function. Ex:
fputcsv($handle, $data, ';', '"');
fputcsv($handle, $data, ',', '"'); //same default fputcsv($handle, $data);