1

How do I add to a .json file with PHP? Currently, I'm appending a .json file with PHP, but it won't add the data to an existing JSON object. It makes a new object. I need the data all stored in one object, in an external JSON file. Basically, I have a JSON object and want to add more values to it.

$jsonFile = "test.json";
$fh = fopen($jsonFile, 'w');

$json = json_encode(array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it));

fwrite($fh, $json);
Dharman
  • 30,962
  • 25
  • 85
  • 135
copilot0910
  • 431
  • 2
  • 6
  • 19

2 Answers2

14

You can decode the json file to a php array, then insert new data and save it again.

<?php
$file = file_get_contents('data.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[] = array('data'=>'some data');
//save the file
file_put_contents('data.json',json_encode($data));
unset($data);//release memory
Licson
  • 2,231
  • 18
  • 26
2

what's suggested above is the hard way. i am considering there should be an easier way, to literally append an array into the json file.

here is the algo:

$handle=fopen($jsonFile);
fseek($handle,-1,SEEK_END);
fwrite($handle,$arrayToAdd);
fclose($handle);

but i am not sure it's more cpu/memory efficient to do so than reading the whole json file into memory, adding the array and then getting it stored.

  • Yes it did waste much less memory & CPU to do so. However when the data structure changes you need to modify your code for that. – Licson Sep 13 '13 at 09:43