我必须做CSV文件导出,该文件必须有ISO-8859-2字符编码,并正确显示外文字符。
控制器如下所示:
public function exportAction(Request $request) {
$repository = $this->getDoctrine()
->getManager()
->getRepository('AdminBundle:ShopPayroll');
$request = $this->get('request');
$response = $this->render('AdminBundle:Payroll:csv.html.twig', [
'list' => $repository->getSomeData()
]);
$handle = fopen('php://memory', 'r+');
$header = array();
fputcsv($handle, (array)utf8_decode($response));
rewind($handle);
$content = stream_get_contents($handle);
fclose($handle);
$response->setCharset('ISO-8859-2');
$response->headers->set('Content-Type', 'text/csv; charset=ISO-8859-2');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
$response->prepare($request);
return $response->send();
}以及csv.html.twig文件本身(文件编码为ISO8859-2):
{% for payroll in list %}
{{ payroll.fvatName|slice(0,32)|lower|title|raw|convert_encoding('UTF-8', 'ISO-8859-2') }}
{% endfor %}好的,它确实以ISO-8859-2编码方式下载了文件,但是如果字符串变量包含外来字符,它会将这些字符更改为一些奇怪的符号。
我尝试在fputcsv()函数中使用iconv,我尝试使用它作为一个小枝内置函数-没有工作。
我该如何解决这个问题?
发布于 2014-10-02 16:08:08
解码器()函数与您所想的不完全相同。有一个来自堆栈溢出规则的用户评论很好地解释了它(强调我的):
请注意,utf8_decode简单地将以UTF-8编码的字符串转换为ISO-8859-1.更合适的名称是utf8_to_iso88591。如果您的文本已经在ISO-8859-1中编码,则不需要此功能。如果不想使用ISO-8859-1,则不需要此函数。
您希望从UTF-8转换为,ISO-8859-2,因此此功能完全不合适。
替代方案包括康夫()和编码()。
发布于 2014-10-29 20:54:04
对我来说很管用。
//open file pointer to standard output
$fp = fopen('php://output', 'w');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fclose($fp);
return $response->send();https://stackoverflow.com/questions/26164762
复制相似问题