V
V
Vladislav Radzimovsky2014-08-13 09:34:47
PHP
Vladislav Radzimovsky, 2014-08-13 09:34:47

Why is the json file zeroed out?

Hello!
There was a small problem recently. Under my cron on the server, a script is executed every 2 minutes, each time the script is executed, the data is written to a json file for convenient display and processing by js.
For the whole day there are about 720 records, and not a small file size. For statistics, I backup this file to another directory, but for some reason, when the file is moved, the entire Json file is reset, and only one entry remains there.
Here is the handler code itself, which writes Json data to a file, and backs it up at the end of the day:

if(date("Hi") == '0000' || date("Hi") == '0001'){
  rename($name . '.json', 'Prev_data/' . $name . '_' . date("d") . '.json');
}

if(!file_exists($name . '.json')){
  $fp = fopen($name . '.json', "w"); 
  fwrite($fp, "[ ]");
  fclose ($fp);
}

$json = file_get_contents($name . '.json');
$json = json_decode($json);

array_push($json, array($item => $time, "zdate" => $date));

$json = json_encode($json);
file_put_contents($name . '.json', $json);

Thank you in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Lopatin, 2014-08-13
@Lafafm

Apparently, the backup file is frayed because it is copied several times. Perhaps several instances of the script are working at the same time, or you messed up something in crontab.
Try replacing date("d") with date("U") and see what happens. If I'm right, then several backup files will be created every day.

D
Dmitry Skogorev, 2014-08-13
@EnterSandman

Attiebut w y fopen
Opens a file for writing only; places the pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, it tries to create it.
Honestly, I read the code in a glimpse from the mobile, but I'm sure that this is it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question