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?
Using PHP scripting we can store a form value in array format. After that will convert the array into JSON data using json_encode() predefined function. Then at last we can move the data to JSON format file.
Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
To append data to the JSON file we have to store the previous data to a variable. To get the data of our JSON file we will be using the file_get_contents() function. The file_get_contents() reads a file into a string.
This has taken the above c example and moved it over to php. This will jump to the end of the file and add the new data in without reading all the file into memory.
// read the file if present
$handle = @fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
$handle = fopen($filename, 'w+');
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($event) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($event)));
}
// close the handle on the file
fclose($handle);
}
$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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With