Save a json file with php inside a bracket and separated by a comma

1

I need a help in php, I only know the basics in the language and I'm wanting save a data.json file, where the form data is sent via post to a data.php file by ajax. in my code the data.php is as follows:

$array = array(); $fp = fopen("dados.json", "a"); $escreve = fwrite($fp, $array[0] = json_encode($_POST)); fclose($fp);

The structure of the data that the data.php generates for the data.json are:

{"nome":"fulano","numero":"1"}

The problem is that I wanted to make a structure in which this data was sent inside a bracket and at the end of each key had a comma, but every time I send the data, it is saved in the data.json is generated the sequence ex:

{"nome":"fulano","numero":"1"}{"nome":"fulano2","numero":"3"}

without being comma-separated, I tried it differently with the following code:

$array = array($_POST); $jsonDados = json_encode($array); $fp = fopen("dados.json", "a"); $escreve = fwrite($fp, $jsonDados); fclose($fp);

The output to the data.json every time the form data is sent is always:

[{"nome":"fulano","numero":"1"}][{"nome":"fulano2","numero":"3"}]

I just want to get this data saved in the following structure:

[{"nome":"fulano","numero":"1"},{"nome":"fulano2","numero":"3"}]

and that every time there is a submission of the form to the data.php, it saves the json by separating the keys with commas within the brackets

If anyone knows I'm very grateful.

    
asked by anonymous 22.01.2018 / 17:27

1 answer

0

You can do it this way:

$dados = json_decode(file_get_contents ("dados.json"));
array_push($dados, $_POST);
$fp = fopen("dados.json", "a");
fwrite($fp, json_encode($dados));
fclose($fp);
    
22.01.2018 / 17:55