gpt4 book ai didi

php - 如何导出为阿拉伯语的 excel?

转载 作者:行者123 更新时间:2023-12-04 19:50:48 25 4
gpt4 key购买 nike

我正在尝试将阿拉伯语数据从 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";
?>

如何正确导出这些数据?

最佳答案

根据 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()至少。

关于php - 如何导出为阿拉伯语的 excel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51332859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com