Reputation: 149
I need to append a new object to a JSON array using PHP.
The JSON:
{
"maxSize":"3000",
"thumbSize":"800",
"loginHistory":[
{
"time": "1411053987",
"location":"example-city"
},
{
"time": "1411053988",
"location":"example-city-2"
}
]}
The PHP so far:
$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:
Fatal error: Uncaught Error: Cannot use object of type stdClass as array
and null
as the output for the "loginHistory" object upon saving the JSON file.
Upvotes: 5
Views: 16933
Reputation: 952
This is a small and simple guide on how to modify a JSON file with PHP.
// Load the file
$contents = file_get_contents('data.json');
// Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);
// Create a new History Content.
$newContent = [
'time'=> "1411053989",
'location'=> "example-city-3"
];
// Add the new content data.
$contentsDecoded['loginHistory'][] = $newContent;
// Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);
// Save the file.
file_put_contents('data.json', $json);
A step-by-step explanation of the code above.
We loaded the contents of our file. At this stage, it is a string that contains JSON data.
We decoded the string into an associative PHP array by using the function json_decode. This allows us to modify the data.
We added new content to contentsDecoded variable.
We encoded the PHP array back into a JSON string using json_encode.
Finally, we modified our file by replacing the old contents of our file with the newly-created JSON string.
Upvotes: 2
Reputation: 723
The problem is that json_decode doesn't return arrays by default, you have to enable this. See here: Cannot use object of type stdClass as array?
Anyway, just add a parameter to the first line and you're all good:
$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 enabled PHP errors/warnings you would see it like this:
Fatal error: Cannot use object of type stdClass as array in test.php on line 6
Upvotes: 3
Reputation: 191729
$accountData
is an object, as it should be. Array access is not valid:
array_push($accountData->loginHistory, $newLoginHistory);
// or simply
$accountData->loginHistory[] = $newLoginHistory;
Upvotes: 2