2

I want to write JSON data to a text file using jQuery and PHP. I send the data from JavaScript to a PHP file using

function WriteToFile(puzzle)
    {
    $.post("saveFile.php",{ 'puzzle': puzzle },
        function(data){
            alert(data);
        }, "text"
    );
    return false;
    }

The PHP file is

<?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;

?>

This works but the output in the file new.json looks like this:

"{\\\"answers\\\":[\\\"across\\\",\\\"down\\\"],\\\"clues\\\":[],\\\"size\\\":[10,10]}"

I don't want those slashes: how did I get them?

Chris
  • 44,602
  • 16
  • 137
  • 156
mfadel
  • 887
  • 12
  • 32

2 Answers2

2

Try using http://php.net/manual/en/function.stripslashes.php , I want to assume you are already receiving a json encoded data form 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;

Sample

    $data = "{\\\"answers\\\":[\\\"across\\\",\\\"down\\\"],\\\"clues\\\":[],\\\"size\\\":[10,10]}" ;
    var_dump(stripslashes($data));

Output

    string '{"answers":["across","down"],"clues":[],"size":[10,10]}' (length=55)
Baba
  • 94,024
  • 28
  • 166
  • 217
1

You don't need to use json_encode as you are taking data from JSON, not putting it in to 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;
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • the output after your edit looks like this: {\"answers\":[\"across\",\"down\"],\"clues\":[],\"size\":[10,10]} I still get this slash – mfadel Mar 27 '12 at 09:36