2

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

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

非常感谢您对这个问题的任何了解!请原谅可怜的变量名。

4

2 回答 2

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.'"');
于 2012-04-28T23:13:29.033 回答
0

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

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

于 2012-04-28T17:48:24.953 回答