5

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;
}
Frank Parent
  • 2,136
  • 19
  • 33

1 Answers1

17

Apply utf8_decode to all elements in result row, so simply array_map:

fputcsv($fp, array_map('utf8_decode',array_values($row)), ',', '"');
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85