I create csv file with fputcsv. I want csv file to be in windows1251 ecnding. But can't find the solution. How can I do that? Cheers
Default encoding for an excel file is machine specific ANSI, mainly windows1252
. But since you are creating that file and maybe inserting UTF-8 characters, that file is not going to be handled ok.
You could use iconv()
when creating the file. Eg:
function encodeCSV(&$value, $key){
$value = iconv('UTF-8', 'Windows-1252', $value);
}
array_walk($values, 'encodeCSV');
windows1252
for EN-US –
Langmuir It's Working: Enjoy
use this before fputcsv:
$line = array_map("utf8_decode", $line);
utf8_decode
cannot convert UTF-8 to windows1251. See PHP documentation. –
Liba utf8_decode
and utf8_encode
functions only work with ISO-8859-1. Using them for anything else is wrong. That is also stated as a note in the documentation. Also this function is deprecated in the upcoming PHP 8.2.0. –
Liba The file will be in whatever encoding your strings are in. PHP strings are raw byte arrays, their encodings depends on wherever the bytes came from. If you just read them from your source code files, they're in whatever you saved your source code as. If they're from a database, they're in whatever encoding the database connection was set to.
If you need to convert from one encoding to another, use iconv
. If you need more in-depth information, see here:
,
and "
used in the CSV files are encoded differently, like UTF-16? –
Talkative "
and ,
to fputcsv
as parameters. (Haven't actually tried it though, but would be my first attempt.) –
Copperplate fputs( $fp, $bom = chr(0xEF) . chr(0xBB) . chr(0xBF) );
Try this it worked for me!!!
fputs
like above and then fputcsv
right after that fixed it for me, too. BOM is the byte order mark which Excel needs to display umlauts and special character correctly, especially on Mac. –
Mckinley Try the iconv function:
http://php.net/manual/en/function.iconv.php
To transform the members of the array you're passing to the fputcsv function to the encoding you want.
$string = iconv(mb_detect_encoding($string), 'Windows-1252//TRANSLIT', $string);
© 2022 - 2024 — McMap. All rights reserved.