我有这个代码用于以CSV格式导出查询,问题是,如果我用Excel打开它,俄语字符将不会显示,但如果我用数字(Mac)打开它们就会显示。 / p>
现在,我无法解决这个问题。我添加了一些我在互联网上看到的线条而没有...
<?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";
}
?>
答案 0 :(得分:6)
未为UTF-8编码数据创建脚本。它几乎按原样转储数据。生成的CSV文件将包含(可能)有效的UTF-8编码数据,但不包含签名。在没有签名的情况下,某些软件会使用启发式方法来检测编码;其他人,比如Excel,不会。
您必须告诉excel将文件视为UTF-8编码。为此,您需要在Excel中导入文件(数据&gt;获取外部数据&gt;从文本中)而不是直接打开它(双击或使用文件&gt;打开)。在文本导入向导中,选择适当的编码,Excel应正确导入数据。请参阅下面的屏幕截图。
或者,您可以尝试添加UTF-8 signature manually。我自己没试过。
// ...
header('Content-Disposition: attachment;filename=hostess.csv');
echo "\xEF\xBB\xBF";
// ...