4

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 'null' as the output for the "loginHistory" object upon saving the JSON file.

3 Answers 3

3

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

2

$accountData is an object, as it should be. Array access is not valid:

array_push($accountData->loginHistory, $newLoginHistory);
// or simply
$accountData->loginHistory[] = $newLoginHistory;
2
  • Except $newLoginHistory should be an object. Sep 18, 2014 at 15:56
  • 1
    @AbraCadaver If it contains 'string' keys, it will be when serialized.
    – Yoshi
    Sep 18, 2014 at 15:58
1

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.

  1. We loaded the contents of our file. At this stage, it is a string that contains JSON data.

  2. We decoded the string into an associative PHP array by using the function json_decode. This allows us to modify the data.

  3. We added new content to contentsDecoded variable.

  4. We encoded the PHP array back into a JSON string using json_encode.

  5. Finally, we modified our file by replacing the old contents of our file with the newly-created JSON string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.