PHP – 将Unicode转换为CSV,例如中文字符

通过表单发布,我们将数据传递给PHP脚本,为电子表格程序(例如excel)创build可下载的CSV。 如果没有特殊的字符通过,下面的scipt工作完美。 但是通过像中文字母这样的特殊字符结束于unicode ….

例如:我们通过表单字段发送“你好世界”(hello world,unicode:坶Ç世界)到这个php脚本export.php

<?php //opens a download dialog, download by excel header("Content-type: text/csv; charset=UTF-8"); header("Content-Disposition: attachment; filename=\"eCalc Results.csv\""); echo html_entity_decode(urldecode($_POST["exportData"])); // returns unicode 你好世界 ?> 

我们如何才能将这个Unicode的Unicode转换成中文字母再次正确地显示为你好世界…?

这里的例子: http : //s4a.ch/exporttest/hello.php

我们search了整个stackoverflow,但没有转换成功…

感谢您的帮助eCalc

find了一个解决scheme:

首先不是用javascript encode(),而是用encodeURI()对发送端进行编码并使用

 <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> 

在标题中。

…和这里的export.php(BOM插入!!)

 <?php header("Content-Encoding: UTF-8"); header("Content-Disposition: attachment; filename=\"eCalc Results.csv\""); header("Content-type: text/csv; charset=UTF-8"); echo "\xEF\xBB\xBF"; // first send the UTF-8 BOM for Excel echo html_entity_decode(urldecode($_POST["exportData"])); ?> 

您可以查看PHP文档的这一部分: http : //php.net/manual/en/function.utf8-encode.php