我正在尝试在服务器上保存一些数据,但发现了一些编码问题。
这就是我将对象发送到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中转换回正确格式的一种方式非常感谢有关此问题的任何亮点!请原谅可怜的变量名。
答案 0 :(得分:0)
如果您使用的是PHP&gt; = 5.4.0,则可以在json_encode函数中使用JSON_UNESCAPED_UNICODE选项。有关详细信息,请查看php.net: json_encode。
对于PHP&lt; 5.4.0,有一些关于如何在同一页面上的用户贡献说明中执行此操作的注释,但不确定它是否能正常工作。
答案 1 :(得分:0)
@ 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.'"');