S
S
SteepNET2022-02-02 17:47:37
PHP
SteepNET, 2022-02-02 17:47:37

Append to json file and read it with php?

Good afternoon!
A little confused in JSON in PHP
The task is to write data to a text file or to a json file data, but not just write, but add new data, a kind of database. so at the moment it’s more convenient, I understand that it’s better to use the database, but I want to use the file first.

I try like this

$datetime = date("Y-m-d H:i:s");
$date = date("Y-m-d");
$time = date("H:i:s");

$array = [
  'Дата' => $datetime,
  'День' => $date,
  'Время' => $time, 
  ];
$json = json_encode($array, JSON_UNESCAPED_UNICODE);

$filename = 'trunk_hook_json.json';
file_put_contents($filename,$json,FILE_APPEND | LOCK_EX);

echo $json;
exit();


The data is successfully written to the file
{"Date":"2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"}

If again I execute the code, it turns out like this
{"Date":"2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"}{"Date ":"2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"}

Then I read like this
$Json = file_get_contents('trunk_hook_json.json');
$array = json_decode($Json);
var_dump($array);


The result is displayed if there is one record in the file, if there are two, then it displays null
Tell me what I'm doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Immortal_pony, 2022-02-03
@SteepNET

Instead of

file_put_contents($filename,$json,FILE_APPEND | LOCK_EX);

... write like this:
$payload = file_exists($filename) ? ",{$json}]" : "[{$json}]"; 
$fileHandler = fopen($filename, "c");
fseek($fileHandler, -1, SEEK_END);
fwrite($fileHandler, $payload);
fclose($fileHandler);

V
Vitsliputsli, 2022-02-02
@Vitsliputsli

The result is displayed if there is one record in the file, if there are two, then it displays null

Because
{"Date":"2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"}{"Date":" 2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"}
is not a valid json. A valid one would be, for example, like this:
[{"Date":"2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"} ,{"Date":"2022-02-02 17:40:12","Day":"2022-02-02","Time":"17:40:12"}]
In any case, append json will not work. Or process it completely and completely overwrite the file. Or store in a file in lines and read in lines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question