Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-28 08:12:29
Original
406 people have browsed it

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>
Copy after login

Next, add the new data from the form to the array:

<code class="php">array_push($tempArray, $data);</code>
Copy after login

Now, you can encode the updated array back into a JSON string:

<code class="php">$jsonData = json_encode($tempArray);</code>
Copy after login

Finally, write the new JSON string back to the same file:

<code class="php">file_put_contents('results.json', $jsonData);</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template