0

So let's say I have a HTML page and an input box on it. The user will type something in it, then I'll store it as a variable in JS, and then, can I somehow write the data of that variable to an already existing JSON file on the server?

How can I achieve this using JavaScript and/or PHP?

EDIT: I actually want to know how to write the data of a PHP variable to a JSON file that is in the same directory as the PHP file.

6
  • JS (clientside) can get that variable and handle it, but only a serverside language (PHP) can write to a file. There are many ways to do this, but all of them consist in sending that value to the server (via a form submit, or Ajax) and handling the file modification serverside(get that $_POST or $_GET variable and handle it). Commented Aug 11, 2015 at 21:25
  • That's exactly what I want. I want to know how to write the data of a php variable to a json file that is in the same directory as the .php file itself. Commented Aug 11, 2015 at 21:25
  • 1
    Ok, then, post what you have so far. Were you able to send the variable back to your PHP already, or not yet? Commented Aug 11, 2015 at 21:27
  • 1
    $foo = json_decode(file_get_Contents('stuff.json')); $foo['newkey'] = 'newdata'; file_put_contents('stuff.json', json_encode($foo));, basically Commented Aug 11, 2015 at 21:27
  • 1
    @MarcB json_decode(..., TRUE) to get an associative array. php.net/manual/en/function.json-decode.php Commented Aug 11, 2015 at 21:29

1 Answer 1

1

file_put_contents("json_file.json",json_encode($array));
Result:
{"key":"value","anotherkey":"anothervalue"}

Note: file_put_contents function will overwrite your file!

Edit: appendable:
$array = json_decode(file_get_contents("json_file.json"),true);
$array['your_new_key'] = "your_new_value";
file_put_contents("json_file.json",json_encode($array));

Sign up to request clarification or add additional context in comments.

6 Comments

One question though, is there a php function that doesn't overwrite the current content of the file? Thanks.
file_put_contents("json_file.json",json_encode($array), FILE_APPEND);
But simply appending it will produce invalid JSON -> {"foo":"bar"}{"x":"z"}
@blex yes, you are right :) i writing another code for you
$array = json_decode(file_get_contents("json_file.json"),true); $array['your_new_key'] = "your_new_value"; file_put_contents("json_file.json",json_encode($array));
|

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.