I have an json file embedded inside php file, I would like to add new infromation from form inside json file...
My form is
<form action="process.php" method="POST">
First name:<br>
<input type="text" name="firstName">
<br><br/>
Last name:<br>
<input type="text" name="lastName">
<br><br>
Email:<br>
<input type="text" name="email">
<br><br>
Mobile:<br>
<input type="text" name="mobile">
<br><br>
<input type="submit" value="Submit">
</form>
and the php file is
<?php
$myFile = "data.php";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'firstName'=> $_POST['firstName'],
'lastName'=> $_POST['lastName'],
'email'=>$_POST['email'],
'mobile'=> $_POST['mobile']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
// Push user data to array
array_push($arr_data,$formdata);
//Convert updated array to JSON
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
When I click the submit button, The new data is being added as follow
{
"heroes": [
{
"firstName": "Vijay",
"lastName": "reddy",
"email": "[email protected]",
"mobile": ""
},
{
"firstName": "Paki",
"lastName": "Webb",
"email": "[email protected]",
"mobile": "66464646464"
},
{
"firstName": "sagar",
"lastName": "rawal",
"email": "[email protected]",
"mobile": "98989898"
}
],
"0": {
"firstName": "sagar",
"lastName": "rawal",
"email": "[email protected]",
"mobile": "98989898"
},
"1": {
"firstName": "Purnima",
"lastName": "rawal",
"email": "[email protected]",
"mobile": "98652845"
}
}
But I want to have data as
{
"heroes": [
{
"firstName": "Vijay",
"lastName": "reddy",
"email": "[email protected]",
"mobile": ""
},
{
"firstName": "Paki",
"lastName": "Webb",
"email": "[email protected]",
"mobile": "66464646464"
},
{
"firstName": "sagar",
"lastName": "rawal",
"email": "[email protected]",
"mobile": "98989898"
},
{
"firstName": "sagar",
"lastName": "rawal",
"email": "[email protected]",
"mobile": "98989898"
},
{
"firstName": "Purnima",
"lastName": "rawal",
"email": "[email protected]",
"mobile": "98652845"
}
]
}
i.e remove the index and write the new data inside json along with other data...so far I couldn't do ...so please help me...Thanks in advance.
heroesarray, then you'll need to add it to that array, not to the object that containsheroes.