使用php将mysqli数据导出到excel时,所有字段均显示在一栏中

时间:2018-07-14 17:02:15

标签: php excel mysqli

我已经编写了一个简单的PHP脚本来下载excel文件,其中包含通过MySQLI查询获取的一些MySQLI数据,当我使用英语数据时,它运行良好,但是当我使用utf 8语言(如阿拉伯语)时,它显示了所有数据在excel文件的一列中

这是代码,我们将不胜感激。

<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'test_db');
mysqli_query($conn, "set names 'utf8'");
setlocale(LC_ALL, 'en_US.UTF-8');

$sql = "SELECT `user_name`,`user_q1`,`user_q2`,
                `user_q3`,`user_q4`,`user_q5` 
        FROM    `usertable`";

$setRec = mysqli_query($conn, $sql);

$columnHeader = '';
$columnHeader = "الاسم" . "\t" . "الاجابة 1" . "\t" . "الاجابة 2" . "\t". "الاجابة 3" . "\t". "الاجابة 4" . "\t". "الاجابة 5" . "\t";

$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
    $rowData = '';
    foreach ($rec as $value) {
        $value = '"' . $value . '"' . "\t";
        $rowData .= $value;
    }
    $setData .= trim($rowData) . "\n";
}

header("Content-type: application/octet-stream");

header("Content-Disposition: attachment; filename=User_Detail.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>

1 个答案:

答案 0 :(得分:0)

多亏了mehdi,我通过使用fputcsv解决了这个问题