Add data to .JSON file using PHP

I have this .json file:

[ { "id": 1, "title": "Ben\\ First Blog Post", "content": "This is the content" }, { "id": 2, "title": "Ben\\ Second Blog Post", "content": "This is the content" } ] 

This is my PHP code:

 <?php $data[] = $_POST['data']; $fp = fopen('results.json', 'a'); fwrite($fp, json_encode($data)); fclose($fp); 

The fact is that I'm not quite sure how to achieve this. I am going to call this code above every time I submit the form, so I need to increase the identifier and also keep the actual JSON structure with [ and { , is this possible?

+11
source share
7 answers
 $data[] = $_POST['data']; $inp = file_get_contents('results.json'); $tempArray = json_decode($inp); array_push($tempArray, $data); $jsonData = json_encode($tempArray); file_put_contents('results.json', $jsonData); 
+32
source

This is taken above, for example, and moved it to php. This will move to the end of the file and add new data without reading the entire file in memory.

 // read the file if present $handle = @fopen($filename, 'r+'); // create the file if needed if ($handle === null) { $handle = fopen($filename, 'w+'); } if ($handle) { // seek to the end fseek($handle, 0, SEEK_END); // are we at the end of is the file empty if (ftell($handle) > 0) { // move back a byte fseek($handle, -1, SEEK_END); // add the trailing comma fwrite($handle, ',', 1); // add the new json string fwrite($handle, json_encode($event) . ']'); } else { // write the first event inside an array fwrite($handle, json_encode(array($event))); } // close the handle on the file fclose($handle); } 
+21
source

You destroy your json data by blindly adding text to it. JSON is not a format that can be manipulated this way.

You will need to load the json text, decode it, process the resulting data structure, then transcode / save it.

 <?php $json = file_get_contents('results.json'); $data = json_decode($json); $data[] = $_POST['data']; file_put_contents('results.json', json_encode($data)); 

Say you have [1,2,3] stored in your file. Your code can turn this into [1,2,3]4 , which is syntactically incorrect.

+14
source

If you want to add another element of the array to the JSON file, as shown in the example, open the file and search to the end. If the file already has data, look back one byte to overwrite ] after the last write, then write , plus new data minus the initial [ new data. Otherwise, this is your first element of the array, so just write your array as usual.

Sorry, I donโ€™t know enough about PHP to publish real code, but I did it in Obj-C, and this allowed me to avoid reading the entire file in the first place, just to add to the end:

 NSArray *array = @[myDictionary]; NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil]; FILE *fp = fopen(fname, "r+"); if (NULL == fp) fp = fopen(fname, "w+"); if (fp) { fseek(fp, 0L, SEEK_END); if (ftell(fp) > 0) { fseek(fp, -1L, SEEK_END); fwrite(",", 1, 1, fp); fwrite([data bytes] + 1, [data length] - 1, 1, fp); } else fwrite([data bytes], [data length], 1, fp); fclose(fp); } 
+4
source

Sample code that I used to add an extra JSON array to a JSON file.

 $additionalArray = array( 'id' => $id, 'title' => $title, 'content' => $content ); //open or read json data $data_results = file_get_contents('results.json'); $tempArray = json_decode($data_results); //append additional json to json file $tempArray[] = $additionalArray ; $jsonData = json_encode($tempArray); file_put_contents('results.json', $jsonData); 
+3
source
 /* * @var temp * Stores the value of info.json file */ $temp=file_get_contents('info.json'); /* * @var temp * Stores the decodeed value of json as an array */ $temp= json_decode($temp,TRUE); //Push the information in temp array $temp[]=$information; // Show what new data going to be written echo '<pre>'; print_r($temp); //Write the content in info.json file file_put_contents('info.json', json_encode($temp)); } 
0
source

I wrote this PHP code to add JSON to a JSON file. The code will enclose the entire file in square brackets and separate the code with commas.

 <?php //This is the data you want to add //I am getting it from another file $callbackResponse = file_get_contents('datasource.json'); //File to save or append the response to $logFile = "results44.json"; //If the above file does not exist, add a '[' then //paste the json response then close with a ']' if (!file_exists($logFile)) { $log = fopen($logFile, "a"); fwrite($log, '['.$callbackResponse.']'); fclose($log); } //If the above file exists but is empty, add a '[' then //paste the json response then close with a ']' else if ( filesize( $logFile) == 0 ) { $log = fopen($logFile, "a"); fwrite($log, '['.$callbackResponse.']'); fclose($log); } //If the above file exists and contains some json contents, remove the last ']' and //replace it with a ',' then paste the json response then close with a ']' else { $fh = fopen($logFile, 'r+') or die("can't open file"); $stat = fstat($fh); ftruncate($fh, $stat['size']-1); fclose($fh); $log = fopen($logFile, "a"); fwrite($log, ','.$callbackResponse. ']'); fclose($log); } ?> 

Good luck

0
source

Source: https://habr.com/ru/post/900078/


All Articles