【问题标题】:When exported to CSV russian characters won't display导出为 CSV 时不会显示俄语字符
【发布时间】:2012-06-28 16:55:03
【问题描述】:

我有这段代码,用于在 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";
}
?>

【问题讨论】:

  • 在导入 csv 时 Excel 是否使用正确的字符编码?
  • 请问这是什么意思?
  • 在您的 php 中,您以 utf-8 输出,这允许处理俄语中的所有字符。将文件导入 Excel 时,Excel 可能未使用 utf-8,因此使用了不同的编码,一种不支持俄语字符的编码,例如 ASCII。
  • superuser.com/questions/280603/… 这应该会有所帮助。导入文件时需要确保 excel 使用的是 utf-8。
  • Excel 在编码方面臭名昭著。这不是你的错,是 Excel 的错。因此投票以离题结束。

标签: php mysql csv character-encoding export-to-csv


【解决方案1】:

脚本不是为 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";
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多