我想使用jQuery和PHP将JSON数据写入文本文件。我使用
将数据从JavaScript发送到PHP文件function WriteToFile(puzzle)
{
$.post("saveFile.php",{ 'puzzle': puzzle },
function(data){
alert(data);
}, "text"
);
return false;
}
PHP文件是
<?php
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["puzzle"]; /* What we'll write to the file */
echo $towrite;
$openedfile = fopen($thefile, "w");
$encoded = json_encode($towrite);
fwrite($openedfile, $encoded);
fclose($openedfile);
return "<br> <br>".$towrite;
?>
这可行,但文件new.json
中的输出如下所示:
"{\\\"answers\\\":[\\\"across\\\",\\\"down\\\"],\\\"clues\\\":[],\\\"size\\\":[10,10]}"
我不想要那些斜线:我是怎么得到它们的?
答案 0 :(得分:2)
尝试使用http://php.net/manual/en/function.stripslashes.php,我想假设您已经收到了json编码的json编码数据
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["puzzle"]; /* What we'll write to the file */
$openedfile = fopen($thefile, "w");
fwrite($openedfile, stripslashes($towrite));
fclose($openedfile);
return "<br> <br>".$towrite;
示例
$data = "{\\\"answers\\\":[\\\"across\\\",\\\"down\\\"],\\\"clues\\\":[],\\\"size\\\":[10,10]}" ;
var_dump(stripslashes($data));
输出
string '{"answers":["across","down"],"clues":[],"size":[10,10]}' (length=55)
答案 1 :(得分:1)
您在从JSON获取数据时不需要使用json_encode
,而不是将其放入JSON中:
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["puzzle"]; /* What we'll write to the file */
$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
return "<br> <br>".$towrite;