Adding New Data to a JSON File with PHP
You aim to append data to an existing JSON file after a form submission. It's essential to maintain a valid JSON structure and increment the ID with each new entry. To accomplish this:
First, read the existing JSON file and decode its contents into a PHP array:
<code class="php">$inp = file_get_contents('results.json'); $tempArray = json_decode($inp);</code>
Next, add the new data from the form to the array:
<code class="php">array_push($tempArray, $data);</code>
Now, you can encode the updated array back into a JSON string:
<code class="php">$jsonData = json_encode($tempArray);</code>
Finally, write the new JSON string back to the same file:
<code class="php">file_put_contents('results.json', $jsonData);</code>
With this code, you can append new data to the JSON file while ensuring a continues incrementing ID and maintaining the proper JSON structure.
The above is the detailed content of How to Append New Data to a JSON File with PHP While Maintaining Structure and Incrementing IDs?. For more information, please follow other related articles on the PHP Chinese website!