A
A
Alexander2018-10-06 16:04:37
PHP
Alexander, 2018-10-06 16:04:37

Why is json written incorrectly?

This is how I set the variables

$content = ["$emailr" => "$passwordr"];
$contentJson = json_encode($content);
file_put_contents($filename,$contentJson, FILE_APPEND );

json content:
{
  "[email protected]": "123Qwe123",
  "[email protected]":"Qwe123Qwe"
}

When I add via php, enters like this:
{
  "[email protected]": "123Qwe123",
  "[email protected]":"Qwe123Qwe"
}{"[email protected]":"123Qwe123"}

What to do so that he would be recorded to the previous two?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2018-10-06
@AleksandrB

Everything is right for you. Exactly what you wrote and no magic. You create a json string, you write it to the end of the file, and that's it. You are not adding new data to the json string that is in the file. You just write a string to the file: {...}{...}{...}{...}...
You need to redo your code, first read the file, then convert the data to json, add your data there , convert back to a string, and overwrite the file.

$json = file_get_contents($filename);
$array = json_decode($json);
$array[$emailr] = $passwordr;
file_put_contents($filename, json_encode($array));

You also need to take into account that the file may turn out to be empty or broken, that is, add error checks, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question