简体   繁体   中英

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\élai de livraison" . And "\é" 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM