I want to generate and save a CSV file with "Windows-1252" encoding.
My base code :
$filename = 'path/to/file.csv';
$file = fopen($filename, 'w');
$datas[] = [
"data 1",
"data 2",
"data 3",
// ...
];
foreach ($datas as $data) {
fputcsv($file, $data, ';');
}
fclose($file);
I tried to add some header :
$options = [
'http'=> [
'header'=>
"Content-Encoding: Windows-1252\r\n" .
"Content-Type: text/csv; charset=Windows-1252\r\n"
]
];
$context = stream_context_create($options);
$file = fopen($tmpFile, 'w', false, $context);
And convert each lines before calling fputcsv() :
foreach ($datas as $key => $data) {
foreach ($data as $line) {
// I tried this :
$datas[$key] = iconv('UTF-8', 'Windows-1252', $line);
// and this :
$datas[$key] = mb_convert_encoding($line, 'Windows-1252');
}
fputcsv($file, $datas, ';');
}
But without success :
$ file --mime-encoding *
file.csv: utf-8
What else should I do ?
Many thanks.
I finally found a solution, by abandoning
fputcsv()
and replacing it with afwrite()
of my line after havingmb_convert_encoding()
it in "Windows-1252".It's not as pretty, but it works :)