【问题标题】:Hebrew issue when creating csv file using php使用 php 创建 csv 文件时的希伯来语问题
【发布时间】:2015-06-17 10:51:39
【问题描述】:

我有这个代码:

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('שדה 1', 'שדה 2', 'שדה 3'));

include('config.php');
$id = 2;
$sql = "SELECT name FROM shoes WHERE event_id = '$id'";
$result = mysqli_query($connection,$sql);

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($result)) fputcsv($output, $row);

第一行没问题,我得到“שדה 1', 'שדה 2', 'שדה 3” 但是我从数据库中得到的信息是这样的:“׳“׳•׳¨ ׳'׳ ׳–׳§ "

为什么不是希伯来语?

你可以在这里得到它: https://eventpay.co.il/1.php

这是我的配置文件:

defined('DB_HOST')? null : define('DB_HOST', 'localhost');
defined('DB_USER')?  null : define('DB_USER', '***');
defined('DB_PASS')?  null : define('DB_PASS', '***');
defined('DB_NAME')?  null : define('DB_NAME', '***');

$connection = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME);

if (mysqli_connect_errno($connection)){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    die();
}

mysqli_set_charset($connection, "utf8");

如您所见,我使用“mysqli_set_charset”。 另外,我所有的数据库排序规则都是utf8_general_ci。 在我的其他 php 文件中,细节很好(来自数据库)。

谢谢。

【问题讨论】:

    标签: php csv utf-8 export-to-csv hebrew


    【解决方案1】:

    我从您的网站下载了 CSV。这是最有用的 - 如果只有所有人在提问时都这样做:)

    检查显示第一行是希伯来语/Windows-1255 编码,而第二行是 UTF-8 编码。使用像 Notepad++ 这样的文本编辑器查看文件,并尝试在编码类型之间进行交换。十六进制编辑器证实了我的怀疑。

    这意味着您的源代码是用 8 位希伯来语编码编写的,而您的数据库正确包含 UTF-8 字符。两个字符串都逐字返回给客户端。

    第一行看起来是正确的,因为您用来查看 .csv 的文件也在 Windows-1255 模式下运行。我怀疑您使用的是 Excel,这可以解释结果。

    由于您不能保证每个人都使用 Windows-1255/Hebrew 代码页,因此您最好将源代码更改为 UTF-8 编码。这意味着,您源代码中字符的非 ASCII 输出将以 UTF-8 格式输出。

    如果您使用 Excel,您现在遇到的问题是告诉 Excel 将文件视为 UTF-8。 UTF-8 字节顺序标记解决了这个问题。它允许 Excel 工作,但需要注意 - 并非所有纯文本编辑器都能理解它。

    添加 UTF-8 BOM:

    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');
    
    // UTF-8 BOM
    fwrite($output, "\xEF\xBB\xBF");
    
    // output the column headings
    fputcsv($output, array('שדה 1', 'שדה 2', 'שדה 3'));
    

    请看以下文章:

    【讨论】:

    • 感谢您的评论,我已尝试将这一行添加到我的文件中,但没有任何不同。我想我没有理解您的解决方案,该怎么办?我试图在没有 bom 的情况下将 unicode 更改为 utf-8,但我得到“标头已发送......”。我应该怎么做?感谢和对不起我的英语!
    • 您是否更改了源文件的编码?
    • @DorBenZaken - 你的英语很棒 - 无需道歉!我相信您最近出现错误的原因是因为我建议您在使用原始输出时使用echo。我已经更新了写入文件描述符的答案。让我知道这是否有效。
    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多