I am working on a Symfony 2 app that should create a CSV File for download:
sep=;
{% for header in headers %}{{ header|trans({}, 'app') }};{% endfor %}
{% for row in data %}
{% for column in row %}{{ column }};{% endfor %}
{% endfor %}
And the Controller:
...
$response = new Response();
$response->headers->set('Content-Type', 'text/csv; charset=UTF-16LE');
$response->headers->set('Content-Disposition', 'attachment;filename="PaymentList.csv"');
$variables = array(
'headers' => $headers,
'data' => $data,
);
// Use UTF-16LE with BOM to be compatible with Excel on Win and Mac
$content = $this->renderView('AppBundle:Shop:export.csv.twig', $variables);
$content = chr(255) . chr(254) . mb_convert_encoding($content, 'UTF-16LE', 'UTF-8');
$response->setContent($content);
return $response;
This works very well and the CSV file can be used in Excel both on Windows and Mac OS X. However, the file should also be used in a quite old accounting tool that expects \r\n
line breaks, while the Twig produces \n
line breaks.
Is there any way to tell Twig to use \r\n
instead?
Of course I could simply search/replace the line breaks in PHP after rendering the view. Another solution would be, to create the CSV Data completely in PHP without involving Twig at all.
Both solution would work, but I form my point of view that would not be very clean. I would like to control the output, that is created by Twig. Is this possible?