Answer the question
In order to leave comments, you need to log in
How to save form data to json file?
Using the script below, I save the post data in the json file, save it in this form:
{"name":"Bot","email":"[email protected]"}
{"name":"Bot","email":"[email protected]"}{"name":"Bot","email":"[email protected]"}{"name":"Bot" ,"email":"[email protected]"}
[{"name":"Bot","email":"[email protected]"},{"name":"Bot2","email":"[email protected]"}]
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$arr = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
$json_string = json_encode($arr);
file_put_contents($file, $json_string, FILE_APPEND);
// echo $json_string;
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<div style="text-align: center;">
<h1>Form</h1>
<form name="form1" method="post" action="">
<p>
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Your full name" autofocus required>
</p>
<p>
<label for="email">Email: </label>
<input type="email" name="email" id="email">
</p>
<p style="text-align: center;">
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
</div>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
I added lines of code where, using str_replace, I achieve the desired format, but somehow it's all crooked :(
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$arr = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
$json_string = json_encode($arr);
file_put_contents($file, '['.$json_string.']', FILE_APPEND);
}
// Если включены строгие типы, то есть объявлено (strict_types=1);
$file = file_get_contents('data.json', true);
$file = str_replace('][', ',', $file);
echo $file;
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question