I
I
Ivan2020-05-08 18:30:06
JSON
Ivan, 2020-05-08 18:30:06

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]"}

Each time you click on the Submit button, the data in the json file is simply added like this:

{"name":"Bot","email":"[email protected]"}{"name":"Bot","email":"[email protected]"}{"name":"Bot" ,"email":"[email protected]"}

How to make the data continue to be saved to a valid json file, following this pattern:

[{"name":"Bot","email":"[email protected]"},{"name":"Bot2","email":"[email protected]"}]

Form code:

<?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>


Thank you!

ps I just need to save the data from the input entered on the site, so that later I can display it on the site in the form of a tag cloud. Something like "Today we were searched", but without MySQL

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2020-05-08
@9StarRu

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 question

Ask a Question

731 491 924 answers to any question