PHP: Will not write to JSON file

Ok, I have some PHP that is supposed to: Read a JSON file, Push a key/value pair to the JSON file, then write it (kind of like a Database):

$file = fopen("database.json","w+");
$dbobj = fread($file,filesize("database.json"));

$db = json_decode($dbobj, true);

$db["key1"] = "value1";
$db["key2"] = "value1";
$db["key3"] = "value1";

$encoded = json_encode($db);
echo $encoded;

which, yes does write key1, key2, and key3.


But, when you remove key3 and add key4 like so:

$db["key1"] = "value1";
$db["key2"] = "value1";
// $db["key3"] = "value1";
$db["key4"] = "value1";

The JSON output does not contain key3:


This is kind of strange. I also tried file_put_contents(); instead of fwrite(); which did nothing.

the mode w+ usually means to erase the contents of a file first, not sure if PHP does anything unusual there. so $dbobj might be empty here. although if it were, what is json_decode doing not to complain that “” is not valid JSON? maybe PHP is a little weird there too.

For some reason r+ and c+ is doing the same thing

only changing w+ to r+ shouldn’t do the same thing, but it shouldn’t fully fix it either. with r+, it skips that truncate-to-zero-length step, so you can read successfully. but by then the file is positioned at the end and the fwrite effectively appends. maybe json_decode is being clever and stopping at the end of the first valid json string. you’d end up parsing the contents next time into the same old dictionary as before.

1 Like

Ok, so I just used file_get_contents() which somehow worked

$file = file_get_contents("database.json");

$db = json_decode($file, true);

$db["key1"] = "value1";
$db["key2"] = "value1";
$db["key3"] = "value1";

echo var_dump($db) . "<br><br>";
$encoded = json_encode($db);
echo $encoded;
$fileobj = fopen("database.json", 'w');