Using PHP, I'm exporting results of a query to CSV. My problem comes when the data contains accent; they are not exported correctly and I lose them all in the generated file.
I used the utf8_decode()
function to manually convert the headers and it worked perfectly, but I don't know how to use it for the results array.
Anyone can help me out please!?
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;
}
Instead, this is due to the way Excel and other spreadsheet programs open a CSV file and display the data therein. Basically, spreadsheet programs are designed to be used for calculation purposes, so they tend to apply mathematical formats to numbers when the CSV file is opened directly into the program.
To convert Excel to CSV file without losing data, first, navigate to File and click on Save As. From the Save As type dropdown, select CSV UTF-8(Comma Delimited). Click on Save. This saves the CSV file without losing any characters.
Apply utf8_decode
to all elements in result row, so simply array_map
:
fputcsv($fp, array_map('utf8_decode',array_values($row)), ',', '"');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With