phpencodingutf-16le

Encode file in UTF-16LE in PHP with Byte Order Mask (BOM)


I got a PHP that receive data in POST by my Javascript and I want to write these data in a CSV file. I need to encode this file in UTF-16LE.

What I try is :

1)

$data = $_POST['data'];
$data = iconv("UTF-8","UCS-2LE",$data);

The result when I open it in notepad++ is UCS-2 LE without Byte Order Mask.

2)

$data = $_POST['data'];
$data = mb_convert_encoding($data,"UTF-16LE","UTF-8");

The result is the same as the 1)

If I encode then manually in UTF-16LE with notepad++ I got the perfect result.

How can I get PHP to add a Byte Order Mask to the UTF-16 data?


Solution

  • If you want a BOM, you have to add it manually. For little endian, it is FFFE. So

    $data = $_POST['data'];
    $data = "\xFF\xFE".iconv("UTF-8","UCS-2LE",$data);
    

    should do the trick...

    Source: Wikipedia