-2

Let's say I have a info.JSON file on my server, with the following data:

{"firstName":"John","age":"37"}

And in PHP, I want to add another key/value pair (somebody's middle name for example) to the info.JSON file. If I use the file_put_contents() function, that will overwrite the file completely. For example:

$middleName = array("middleName" => "Bill");
file_put_contents("info.json",json_encode($middleName));

The content of the info.JSON file would now be :

{"middleName":"Bill"}

How can I simply add more key/value pairs to an existing .JSON file without overwriting it?

Thanks.

bool3max
  • 2,748
  • 5
  • 28
  • 57
  • `file_put_contents()` takes a 3rd argument which is called: **flags** and you can pass stuff like: `FILE_APPEND`. You have 1 guess left what this does :) (Read more about the function in the manual) – Rizier123 Aug 11 '15 at 23:19
  • 1
    `json_decode(file_get_contents('info.json'))`, then you'll have a PHP object you can deal with more easily and then write back into the file. – Don't Panic Aug 11 '15 at 23:19
  • 2
    @Rizier123 It seems like just appending to the file would most likely break the JSON, what do you think? – Don't Panic Aug 11 '15 at 23:20
  • Hey, i commented new code to old question :D – cagri Aug 11 '15 at 23:23
  • Yeah, appending content to the file just adds it at the end of the file. And that's not properly formatted JSON. I'll try your solution, @Don't Panic . – bool3max Aug 11 '15 at 23:23

1 Answers1

0

If you use json_decode($json,true) with the true flag so that it would come back as an associative array. Then you can add items using the array syntax and json_encode again before put in file .like this may be

$json=file_get_contents('path/to/your/file);
$temp = json_decode($json,true);
$temp['middleName'] ='Bill';
$json = json_encode($temp);
file_put_contents($json);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103