3

I am trying to export Arabic data from MySQL to Excel, but I get weird symbols, like this: كرة

Here is my code:

<?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";
?> 

How can I properly export this data?

miken32
  • 42,008
  • 16
  • 111
  • 154
anater mj
  • 123
  • 3
  • 11

1 Answers1

0

According to this answer, the only encoding that seems to work consistently is UTF-16LE with a BOM. Try editing your code accordingly:

<?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";
?>

Though you should really be using functions that will do escaping and such for you, like fputcsv() at a minimum.

miken32
  • 42,008
  • 16
  • 111
  • 154