Search code examples
phpcharacter-encodingfwrite

Php fopen or fwrite creates text with unicode


I'm trying to write a file with fopen and fwrite. I have an array that displays fine when printing it.

For instance i can see "Délai de livraison" being printed out.

After creating a file, it is displayed as: "D\u00e9lai de livraison". And "\u00e9" is unicode if I understand right.

I have tried adding a "BOM" and writing it to the beginning of the file, but there is no change.

//Write $newarray to a file   

$filename = 'translations_fr.json';

 //create json file
 $file = base_path('/imports/') . $filename;
 $fp = fopen($file, 'w');

 //BOM 
  fwrite($fp, "\xEF\xBB\xBF");

fwrite($fp, json_encode($newarray));
fclose($fp);

My IDE is Netbeans and it is configured with UTF-8 as default. I tried utf8_encode(), but no luck. What can I do?


Solution

  • It's not a BOM or fwrite() issue. json_encode() will turns all multibyte characters into unicode format, by default.

    But you could use the JSON_UNESCAPED_UNICODE option :

    echo json_encode(['test'=>'délai']);
    echo json_encode(['test'=>'délai'], JSON_UNESCAPED_UNICODE);
    

    Outputs :

    {"test":"d\u00e9lai"}
    {"test":"délai"}
    

    From documentation:

    Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.