Reputation: 2091
I have to download twig file with ISO encoding, but although I changed the response's charset it keeps being an UTF-8 file when I download it.
This is the code of the route handling file download:
public function exportAction() {
$path = 'page/1/sort/userId/order/desc';
$slugs = $this->get('path')->convert($path);
$repository = $this->getDoctrine()
->getManager()
->getRepository('AcmeBundle:Payroll');
$request = $this->get('request');
$response = $this->render('AcmeBundle:Payroll:csv.html.twig', [
'list' => $repository->getCsv(),
'week_txt' => date( "d.m.Y", strtotime("last wednesday"))."-".date( "d.m.Y", strtotime("tuesday this week")),
]);
$handle = fopen('php://memory', 'r+');
$header = array();
fputcsv($handle, (array)$response);
rewind($handle);
$content = stream_get_contents($handle);
fclose($handle);
$response->setCharset('ISO-8859-2');
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $response;
}
What's wrong?
Upvotes: 1
Views: 2001
Reputation: 1738
I've had this problem before, you need to call the prepare()
method of the Response object before sending it to the client, like below.
// ...
$response->setCharset('ISO-8859-2');
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
$response->prepare();
return $response
}
I'm not sure why, I think it's because it prepares the response based on the request received, I can only assume that Symfony detects the difference between the charset of the request and the response and adds the header because of the difference, but this may also be a bug.
The docs for this method are below.
http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Response.html#method_prepare
Upvotes: 2