Converting CSV file to UCS-2LE encoding with php

682 Views Asked by At

I'm creating a csv file. I need it to be in UCS-2LE encoding. I tried the following, neither of which work:

  • $value = mb_convert_encoding($value,"UCS-2LE");
  • $value= iconv( mb_detect_encoding( $value ), 'UCS-2LE', $value );

Opening the file in Notepad++ shows the encoding to be ANSI.

Code:

$file = fopen($filename,"w");
array_walk($csv_data, 'encodeCSV');

foreach ($csv_data as $line) {
    fputcsv($file, explode(',', $line));
}

fclose($file);

function encodeCSV(&$value, $key){
    $value = mb_convert_encoding($value,"UCS-2LE");
    //$value= iconv( mb_detect_encoding( $value ), 'UCS-2LE', $value );
}
1

There are 1 best solutions below

0
On

You should add the byte-order-mark (BOM) at the beginning of the file. This should be '\xff\xfe' in your case:

$file = fopen($filename,"w");
fwrite($file, '\xff\xfe');