我必须进行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文件本身(文件编码为ISO-8859-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,我试着把它用作一个内置的trick函数——没有一个有效。
我该如何解决这个问题?
小时>小时>utf8_decode()函数并不是你想的那样。有一个来自Stack Overflow规则的用户评论非常好地解释了这一点(重点是我的):
请注意,utf8_decode只是转换UTF-8编码的字符串符合ISO-8859-1。一个更合适的名字是utf8_to_iso88591。如果您的文本已经用ISO-8859-1编码,则您不需要此功能。如果你不想使用ISO-8859-1,你可以不需要此功能。
您希望从UTF-8转换为ISO-8859-2,因此此函数完全不合适。
备选方案包括iconv()和mb_convert_encoding()。
它对我有效。
//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();