Home  >  Article  >  Backend Development  >  How to Append New Data to a JSON File with PHP While Maintaining Structure and Incrementing IDs?

How to Append New Data to a JSON File with PHP While Maintaining Structure and Incrementing IDs?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 08:12:29258browse

How to Append New Data to a JSON File with PHP While Maintaining Structure and Incrementing IDs?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn