[英]Foreign characters in ISO-8859-2 encoded file
我必須執行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,我嘗試將其用作細枝內置函數-無用。
我怎么解決這個問題?
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.