11

在 MySQL 中,我将数据字段类型设置为,utf8_bin并且我以 Unicode 存储数据。文本在网页中正确显示。

我想生成将数据从我的表导出到它的 excel 文件。.xls和中的输出.cvs是 - '????'。

我在这里查看其他答案,它被称为使用标题:

header("content-type:application/csv;charset=UTF-8");

类似的问题。但它不起作用。使用标头后,在 csv 中输出为 - सूरà¥à¤¯à¤¾。

请帮忙。谢谢。

4

4 回答 4

21

这篇文章解决了我的问题:https ://stackoverflow.com/a/4762708/2349494

这就是转换的原因:

print chr(255) . chr(254) . mb_convert_encoding($csv_output, 'UTF-16LE', 'UTF-8');

早些时候我得到了垃圾字符,现在导出了正确的数据。

于 2013-07-25T07:45:05.987 回答
13

I had the same problem and I did it by combining two things:

First, you have to change table collation to UTF8 e.g: "utf8_general_ci" (or just make sure of that), then add this code after your MySQL query:

mysql_query("SET NAMES utf8");

Like

$result = mysql_query("SHOW COLUMNS FROM table WHERE Field NOT IN ('user_id', 'password')");
mysql_query("SET NAMES utf8");

And then, use this as header (adapt with your needs):

header('Content-Description: File Transfer');
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
print "\xEF\xBB\xBF"; // UTF-8 BOM
print $csv_output;
exit;
于 2013-07-24T20:24:33.363 回答
5

我有一个 Sajal 响应的变体,并在 php.net 上找到它:http ://www.php.net/manual/en/function.iconv.php#104287

在 csv 内容的开头回显这个:

chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $data)

我更喜欢 withiconv()但它似乎与mb_convert_encoding(). 不要忘记;用制表符(\t)替换,它对我来说很好用!

于 2013-10-15T15:53:26.717 回答
0

尝试以下代码;

ob_end_clean();
$_filename = date('Y_m_d_H_i').".csv";

header("Cache-Control: public"); 
header("Content-Type: application/octet-stream");
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=$_filename");
// Read the file from disk
readfile($filename);
exit();
于 2013-07-11T12:30:41.613 回答