Home  >  Article  >  Backend Development  >  How to Append Data to a .JSON File & Increment IDs in PHP?

How to Append Data to a .JSON File & Increment IDs in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 08:38:02992browse

How to Append Data to a .JSON File & Increment IDs in PHP?

Appending Data to a .JSON File in PHP

You're working with a JSON file and have devised PHP code to append data to it every time a form is submitted. However, there's a need to increment the ID and maintain the JSON structure.

The code you referenced seems to store form data in $data and write it to 'results.json' using fwrite() and json_encode(). While conceptually correct, it is missing crucial elements for creating a valid JSON structure.

The recommended approach is:

<code class="php">$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);</code>

This code starts by converting the existing JSON into a PHP array ($tempArray), pushing the new data ($data) into it, then converting the updated array back into JSON ($jsonData) before writing it to 'results.json'.

This approach ensures the maintenance of the JSON structure and increments the ID seamlessly.

The above is the detailed content of How to Append Data to a .JSON File & Increment IDs in PHP?. 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