转换数据以在导出为CSV之前保留重音

时间:2010-11-08 18:27:15

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

使用PHP,我将查询结果导出为CSV。当数据包含重音时我的问题出现了;它们未正确导出,我在生成的文件中丢失了所有内容。

我使用utf8_decode()函数手动转换标题并且它工作得很好,但我不知道如何将它用于结果数组。

任何人都可以帮助我!?

result = db_query($sql);
if (!$result) die('Couldn\'t fetch records');

$fp = fopen('php://output', 'w');
if ($fp && $result) {
 header("Content-type: application/vnd.ms-excel; charset=UTF-8");
 header('Content-Disposition: attachment; filename="adp_enigmes_data.csv"');
 header('Pragma: no-cache');
 header('Expires: 0');
 fputcsv($fp, $headerTitles);

 while ($row = $result->fetch_array(MYSQLI_NUM)) {
     // When I use utf8_decode here, I don't get any results, so I have
        // no idea where to use it!
        fputcsv($fp, utf8_decode(array_values($row)), ',', '"');
 }
 die;
}

1 个答案:

答案 0 :(得分:15)

utf8_decode应用于结果行中的所有元素,因此只需array_map

fputcsv($fp, array_map('utf8_decode',array_values($row)), ',', '"');