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?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It would be nice if you accept as answer for people to know it has been resolved
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;

1 Comment

the output after your edit looks like this: {\"answers\":[\"across\",\"down\"],\"clues\":[],\"size\":[10,10]} I still get this slash

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.