Last active
October 3, 2024 17:01
-
-
Save zuzuleinen/6db61b09465e9bc8a7ea to your computer and use it in GitHub Desktop.
CSV Response in Symfony controller action
This file contains hidden or 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
<?php | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
class CsvController extends Controller | |
{ | |
/** | |
* Get a CSV file from an array | |
* | |
* @return \Symfony\Component\HttpFoundation\Response | |
*/ | |
public function csvAction() | |
{ | |
$list = array( | |
//these are the columns | |
array('Firstname', 'Lastname',), | |
//these are the rows | |
array('Andrei', 'Boar'), | |
array('John', 'Doe') | |
); | |
$fp = fopen('php://output', 'w'); | |
foreach ($list as $fields) { | |
fputcsv($fp, $fields); | |
} | |
$response = new Response(); | |
$response->headers->set('Content-Type', 'text/csv'); | |
//it's gonna output in a testing.csv file | |
$response->headers->set('Content-Disposition', 'attachment; filename="testing.csv"'); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A bit late, but there is a class called
CsvEncoder
. You can do something like this:The array keys of each element in
$data
are the headers. You can change the header order by doing something like this: