Created
February 16, 2013 20:23
-
-
Save charliepage88/4968586 to your computer and use it in GitHub Desktop.
Symfony 2 CSV Export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id, field1, field2, field3 | |
{% for row in data %} | |
{{ row.id }},{{ row.field1 }},{{ row.field2 }},{{ row.field3 }} | |
{% endfor %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
admin_csv: | |
pattern: /admin/csv | |
defaults: { _controller: AcmeTestBundle:Default:adminCsv } |
$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.
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
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 (: