如何出口到阿拉伯语优秀?

时间:2018-07-13 21:11:39

标签: php excel mysqli unicode

我试图将阿拉伯语数据从MySQL导出到Excel,但出现奇怪的符号, 像这样:كرة

这是我的代码:

<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'crud');
mysqli_query($conn, "set names 'utf8'");
$sql = "SELECT `userid`,`first_name`,`last_name` FROM `employee`";
$setRec = mysqli_query($conn, $sql);
$columnHeader = '';
$columnHeader = "User Id" . "\t" . "First Name" . "\t" . "Last Name" . "\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.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?> 

如何正确导出这些数据?

1 个答案:

答案 0 :(得分:0)

根据this answer,唯一看起来一致的编码是带有BOM的UTF-16LE。尝试相应地编辑代码:

<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'crud');
mysqli_query($conn, "set names 'utf8'");
$sql = "SELECT `userid`,`first_name`,`last_name` FROM `employee`";
$setRec = mysqli_query($conn, $sql);
$columnHeader = '';
$columnHeader = "User Id" . "\t" . "First Name" . "\t" . "Last Name" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
    $rowData = '';
    foreach ($rec as $value) {
        $value = '"' . $value . '"' . "\t";
        $rowData .= $value;
    }
    $setData .= trim($rowData) . "\n";
}
// convert to UTF-16 and add BOM
$setData = chr(255) . chr(254) . mb_convert_encoding($setData, "UTF-16LE", "UTF-8");
// add encoding in headers
header("Content-Encoding: UTF-16LE");
header("Content-type: text/csv; charset=UTF-16LE");

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

尽管您确实应该使用会转义的函数,但至少要像fputcsv()这样。