Ketan
Ketan

Reputation: 123

php export data with accents into csv

I have the following code that creates a csv file:

$data=array();
array_push($data,"Société"); //word with french accent


header('Content-Type:text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="test.csv"');


$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, array_map('utf8_decode',array_values($val)), ',', '"');
}
fclose($fp);

However when I open the csv file, the character é is replaced by a question mark ?.

Any help how to resolve this?

Upvotes: 2

Views: 2858

Answers (3)

Ketan
Ketan

Reputation: 123

I used UTF-8 characters in the string. I replaced

array_push($data,"Société"); //word with french accent

with

array_push($data,"Soci\xc3\xa9t\xc3\xa9"); //word with french accent

Upvotes: 0

Fanghornn
Fanghornn

Reputation: 56

Did you tried removing the "utf8_decode" argument in your array_map call ?

If you call the function "utf8_decode" on a UTF-8 string, it will return it under LATIN-1 encoding which doesn't support accents.

See the PHP documentation of utf8_decode > http://php.net/manual/en/function.utf8-decode.php

Bon courage.

Upvotes: 1

Eun
Eun

Reputation: 4178

I had an similar problem a while ago, I fixed it by adding the 3 byte UTF8 representation before any csv line:

header('Content-Type: application/x-download');
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: attachment; filename="export-'.time().'.csv"');

echo chr(0xEF);
echo chr(0xBB);
echo chr(0xBF);

Upvotes: 0

Related Questions