Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert data to keep accents before exporting to CSV

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;
}
like image 205
Frank Parent Avatar asked Nov 08 '10 18:11

Frank Parent


People also ask

Why does my exported CSV data get converted to weird format?

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.

How do you convert Excel to CSV without changing format?

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.


1 Answers

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

fputcsv($fp, array_map('utf8_decode',array_values($row)), ',', '"');
like image 188
dev-null-dweller Avatar answered Sep 25 '22 22:09

dev-null-dweller