Pregunta

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?

¿Fue útil?

Solución

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)

Otros consejos

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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top