I have this .json file:
[
{
"id": 1,
"title": "Ben\\'s First Blog Post",
"content": "This is the content"
},
{
"id": 2,
"title": "Ben\\'s 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 thing is, I'm not exactly sure how to achieve it. I'm going to call this code above every time a form is submitted, so I need the ID to increment and to also keep the valid JSON structure with [
and {
, is this possible?
My Answer:
Yes, it is possible to append data to a .json file while maintaining the valid JSON structure. Here is an updated version of your PHP code that achieves this:
php
// Read the existing JSON file
$jsonData = file_get_contents('results.json');
$data = json_decode($jsonData, true);
// Get the new data from the form
$newData = $_POST['data'];
// Increment the ID for the new data
$newData['id'] = count($data) + 1;
// Add the new data to the existing data array
$data[] = $newData;
// Write the updated data back to the JSON file
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($data, JSON_PRETTY_PRINT));
fclose($fp);
?>
In this code, we first read the existing JSON data from the file, decode it into a PHP array, and then add the new data to this array. We increment the ID for the new data based on the number of existing entries. Finally, we write the updated data back to the JSON file with `JSON_PRETTY_PRINT` to maintain the valid JSON structure.
Rate this post
4 of 5 based on 9456 votesComments