如何使用 PHP 将 utf-8 编码的 json 保存到.txt文件中


How do I save utf-8 encoded json with PHP to a .txt file

我正在尝试在服务器上保存一些数据,但发现一些编码问题。

这就是我将对象发送到PHP的方式(工作正常,但我认为contentType实际上没有做任何事情(:

$.post(
  'myfile.php',
   {
       contentType: "application/x-www-form-urlencoded;charset=utf-8",
       data : myData
   },
   function (data, textStatus, jqXHR){
      //some code here
   }
);

然后在PHP(myfile.php

(:
<?php
   header('Content-Type: text/html; charset=utf-8');
   $file = 'data/theData.txt'; //the file to edit
   $current = file_get_contents($file); // Open the file to get existing content
   $a2 = json_decode( $current, true );
   $data = $_POST['data']; //the data from the webpage
   $res = array_merge_recursive( $data, $a2 );
   $resJson = json_encode( $res );
   // Write the contents back to the file
   file_put_contents($file, $resJson);
?>

如您所见,我正在获取文件的原始内容并解码 json。然后,我将结果与从网页发送的数据合并,然后重新编码为 json 并将内容放回原处。

这一切都按预期工作。但是,在我的 Jquery 中的某一时刻,发送的数据包含各种各样的符号,例如"/ö é ł Ż ę">

保存文件时,每个"/"前面都有一个转义字符"''",同样,例如"é"是"''u00e9"

如何覆盖它?我应该尝试在 PHP 中正确转换它,还是在我有 $.get('data/theData.txt' 后,他们在 JQuery 中转换回正确的格式?

非常感谢

对此问题的任何说明!请原谅变量名称不佳。

@chalet16提供的链接有所帮助,但如果JSON_UNESCAPED_UNICODE对您不起作用,这就可以完成了工作!

$myString = $json_encode($myObject); 
//After initially encoding to json there are escapes on all '/' and characters like ö é ł Ż ę
//First unescape slashes:
$myString = str_replace("'/","/",$myString);
//Then escape double quotes
$myString = str_replace('"','''"',$myString);
//And Finally:
$myNewString = json_decode('"'.$myString.'"');

如果您使用的是 PHP>=5.4.0,则可以在json_encode函数中使用JSON_UNESCAPED_UNICODE选项。请查看 php.net:json_encode了解更多详情。

对于 PHP <5.4.0,在同一页面上的用户贡献的注释中有一些关于如何执行此操作的评论,但不确定它是否能正常工作。