我必须下载带有ISO编码的twig文件,但是虽然我更改了响应的字符集,但在下载时它仍然是一个UTF-8文件。
这是路由处理文件下载的代码:
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;
}
怎么了?
答案 0 :(得分:2)
之前我遇到过这个问题,你需要先调用Response对象的prepare()
方法,然后再发送给客户端,如下所示。
// ...
$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
}
我不确定原因,我认为是因为它根据收到的请求准备响应,我只能假设Symfony检测到请求的字符集与响应之间的差异并添加标题是因为差异,但这也可能是一个错误。
此方法的文档如下。
http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/Response.html#method_prepare