【问题标题】:How do I save utf-8 encoded json with PHP to a .txt file如何使用 PHP 将 utf-8 编码的 json 保存到 .txt 文件中
【发布时间】:2012-05-08 23:52:55
【问题描述】:

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

这就是我将对象发送到 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 中转换回正确格式?

非常感谢您对此问题的任何启发!请原谅可怜的变量名。

【问题讨论】:

  • @IgnacioVazquez-Abrams:我不认为这是一个骗局。
  • 对 $_POST 值使用 base64_encode() 并将其提供给我们。这为我们保留了字符串二进制安全,因此我们可以告诉您它是否为 utf8。
  • @Alix:Asker 希望他们的 JSON 编码为 UTF-8,而不是带有 Unicode 转义的 ASCII。 PHP 不这样做。
  • @chris 对不起,我的 PHP 生锈了。 $_POST['data'] 值是一个数组,那么我应该如何对其进行 base64 编码?

标签: javascript php jquery json encoding


【解决方案1】:

@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.'"');

【讨论】:

    【解决方案2】:

    如果你使用 PHP >=5.4.0,你可以在 json_encode 函数中使用 JSON_UNESCAPED_UNICODE 选项。详情请关注php.net: json_encode

    对于 PHP

    【讨论】:

    • 谢谢@chalet16 这帮助很大。遗憾的是 JSON_UNESCAPED_UNICODE 选项对我不起作用,但其他 cmets 修复了它。
    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多