Answer the question
In order to leave comments, you need to log in
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();
$Json = file_get_contents('trunk_hook_json.json');
$array = json_decode($Json);
var_dump($array);
Answer the question
In order to leave comments, you need to log in
Instead of
file_put_contents($filename,$json,FILE_APPEND | LOCK_EX);
$payload = file_exists($filename) ? ",{$json}]" : "[{$json}]";
$fileHandler = fopen($filename, "c");
fseek($fileHandler, -1, SEEK_END);
fwrite($fileHandler, $payload);
fclose($fileHandler);
The result is displayed if there is one record in the file, if there are two, then it displays null
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question