Skip to content

Instantly share code, notes, and snippets.

@charliepage88
Created February 16, 2013 20:23
Show Gist options
  • Save charliepage88/4968586 to your computer and use it in GitHub Desktop.
Save charliepage88/4968586 to your computer and use it in GitHub Desktop.
Symfony 2 CSV Export
id, field1, field2, field3
{% for row in data %}
{{ row.id }},{{ row.field1 }},{{ row.field2 }},{{ row.field3 }}
{% endfor %}
public function adminCsvAction() {
$repository = $this->getDoctrine()->getRepository('AcmeTestBundle:Test');
$query = $repository->createQueryBuilder('s');
$query->orderBy('s.id', 'DESC');
$data = $query->getQuery()->getResult(); $filename = "export_".date("Y_m_d_His").".csv";
$response = $this->render('AcmeTestBundle:Default:adminCsv.html.twig', array('data' => $data));
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Description', 'Submissions Export');
$response->headers->set('Content-Disposition', 'attachment; filename='.$filename);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
$response->prepare();
$response->sendHeaders();
$response->sendContent();
return $response;
}
admin_csv:
pattern: /admin/csv
defaults: { _controller: AcmeTestBundle:Default:adminCsv }
@todofixthis
Copy link

You may also want to add {%autoescape false %} to the template to prevent HTML entities from being encoded.

See http://twig.sensiolabs.org/doc/tags/autoescape.html for more info.

Bonus points if you find/write a CSV escaping strategy (:

@phisch
Copy link

phisch commented Nov 26, 2013

$response->sendHeaders();
$response->sendContent();

Manually sending headers and the content is redundant, as return $response; will send both headers and content!

Sending headers twice can lead to problems with the in "Content-Disposition" defined filename. In my case it attached "-, attachment" to the download-filename.

@hvallenilla
Copy link

Only use return $response;
$response->prepare(); is deprecated in 2.4
$response->sendHeaders(); is redundant

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment