I have a question about using PHP with JSON.
I use array to store inside .json file. The array containing the data comes from my index.php and is populated by the user, so far so good. Everything is saved in .json and when I have more than 1 user storing content in it (meaning there are 2 arrays in the .json file), it does not return the data but returns NULL. Am I missing something about saving or reading a JSON file? I found that my JSON was invalid, it was showing me "Multiple root JSON elements" inside the validator.
This is my code for writing and reading .json:
public function JSONwrite($lists) { $listFill = json_encode($lists)."\n"; file_put_contents("/var/www/html/3sprint/test.json",$listFill,FILE_APPEND); } public function JSONread() { $string = file_get_contents("/var/www/html/3sprint/test.json"); $stringContent = json_decode($string, true); var_dump($stringContent); }
My JSON file looks like this (2 arrays populated):
[{"count":"3","name":"testnameone"},{"count":"5","name":"testnametwo"},{"count":"6","name":"testnamethree"},{"info":106}] [{"count":"3","name":"testnamefour"},{"count":"5","name":"testnamefive"},{"count":"6","name":"testnamesix"},{"info":521}]
This is where I populate the array and then pass it to the JSONwrite method (this is inside the foreach loop):
$lists[]= [ "count"=>$count, "name"=>$name ]; } } $lists[]= [ "info" => $number ];
Is there a way to validate it like this so that decoding doesn't return null?
An array under another array is invalid JSON. You should use a root array and keep your users in it (not sure if what's in the array makes sense, but you get the idea):
In other words, it should look like this:
json_decode()
json_encode()
to encode it back