我想使用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
中的输出看起来像这样:
"{'''"answerswers'''":['''"across'''",'''"down'''"],'''"clues'''":[],'''"size'''":[10,10]}"
我不想要那些斜杠:我是怎么得到的?
尝试使用http://php.net/manual/en/function.stripslashes.php,我想假设您已经收到一个json编码的数据表单jquery
$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 = "{'''"answerswers'''":['''"across'''",'''"down'''"],'''"clues'''":[],'''"size'''":[10,10]}" ;
var_dump(stripslashes($data));
输出
string '{"answerswers":["across","down"],"clues":[],"size":[10,10]}' (length=55)
您不需要使用json_encode
,因为您从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, $towrite);
fclose($openedfile);
return "<br> <br>".$towrite;