我有这段代码,用于在 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";
}
?>
最佳答案
脚本不是为 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";
// ...
关于php - 导出为 CSV 俄语字符时不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11223156/