我用这个代码在CSV中导出一个查询,问题是,如果我用Excel打开它,俄文字符不会显示,但如果我用数字(Mac)打开它,它们就会显示。
现在,我不明白这是怎么回事。我添加了一些我在互联网上看到的代码,但什么都没有..
<?php
/*
* PHP code to export MySQL data to CSV
* http://salman-w.blogspot.com/2009/07/export-mysql-data-to-csv-using-php.html
*
* Sends the result of a MySQL query as a CSV file for download
*/
/*
* establish database connection
*/
$conn = mysql_connect('', '', '') or die(mysql_error());
mysql_select_db('', $conn) or die(mysql_error($conn));
mysql_query("SET NAMES UTF8");
/*
* execute sql query
*/
$query = sprintf('SELECT fields FROM table');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
/*
* send response headers to the browser
* following headers instruct the browser to treat the data as a csv file called export.csv
*/
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename=hostess.csv');
/*
* output header row (if atleast one row exists)
*/
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
/*
* output data rows (if atleast one row exists)
*/
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
/*
* echo the input array as csv data maintaining consistency with most CSV implementations
* - uses double-quotes as enclosure when necessary
* - uses double double-quotes to escape double-quotes
* - uses CRLF as a line separator
*/
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>发布于 2012-08-24 01:25:01
该脚本不是为UTF-8编码数据创建的。它几乎按原样转储数据。生成的CSV文件将包含(可能)有效的UTF-8编码数据,但不包含签名。在没有签名的情况下,一些软件将使用启发式方法来检测编码;而其他软件,如Excel,则不会。
您必须告诉excel将该文件视为UTF-8编码。为此,您需要在Excel中导入文件(数据>获取外部数据>从文本),而不是直接打开(双击或使用文件>打开)。在“文本导入向导”中,选择适当的编码,Excel即可正确导入数据。请看下面的截图。
或者,您可以尝试添加UTF-8 signature manually。我自己还没试过。
// ...
header('Content-Disposition: attachment;filename=hostess.csv');
echo "\xEF\xBB\xBF";
// ...


https://stackoverflow.com/questions/11223156
复制相似问题