Adding data to a JSON array using PHP
I need to add a new object to a JSON array using PHP.
JSON:
{
"maxSize":"3000",
"thumbSize":"800",
"loginHistory":[
{
"time": "1411053987",
"location":"example-city"
},
{
"time": "1411053988",
"location":"example-city-2"
}
]}
So far PHP:
$accountData = json_decode(file_get_contents("data.json"));
$newLoginHistory['time'] = "1411053989";
$newLoginHistory['location'] = "example-city-3";
array_push($accountData['loginHistory'],$newLoginHistory);
file_put_contents("data.json", json_encode($accountData));
I keep getting "null" as output for the "loginHistory" object when I save the JSON file.
+3
source to share
2 answers
The problem is that json_decode doesn't return arrays by default, you have to enable that. Look here: Can't you use an object of type stdClass as an array?
Anyway, just add the parameter to the first line and you're good to go:
$accountData = json_decode(file_get_contents("data.json"), true);
$newLoginHistory['time'] = "1411053989";
$newLoginHistory['location'] = "example-city-3";
array_push($accountData['loginHistory'],$newLoginHistory);
file_put_contents("data.json", json_encode($accountData));
If you have enabled PHP errors / warnings, you will see the following:
Fatal error: cannot use object of type stdClass as array in test.php on line 6
+2
source to share