How to generate JSON files through forms?

Asked

Viewed 2,295 times

0

I want to store the data that users put into inputs in separate JSON files so I can use it later. Can someone help me?

  • 1

    Have you tried searching for php and json here on the site? Check this out: https://answall.com/search?q=%5Bphp%5D+json. Surely one of the questions will help you in what you need; at least indicating what you should study.

  • You will need to use the file in the client or backend?

  • i need to show them to the user later

2 answers

0


If you have taken the data via form, you can use the json_encode() before saving the data to the file. Example:

html form.

<form id="form" name="form" method="post" action="save.php">
   <input type="text" name="nome">
   <input type="text" name="sobrenome">
   <input type="submit" value="Enviar">
</form>

save.php (file that receives the form request)

<?php

// Pega a requisição post e transforma em JSON.
$values = json_encode($_POST);

// Armazena no final do arquivo os valores recebidos.
file_put_contents('nome_e_path_do_arquivo.ext', $values, FILE_APPEND);
  • Could you explain this second part of save.php in more detail?

  • What part? Encode or file_put_contents!

  • both, if you have patience and willingness, please.

  • Would you help me if I explained better to you how the project is and what I’m trying to do?

  • It would be good to always explain as much as possible of your problem and doubt. This helps us to provide better answers. But trying to explain a little of what you asked for: json_encode is the method that will transform the entire $_POST array into a json string (as you want); file_put_contents is the method that tries to write some in a file, if the file does not exist, it creates if you have permission in the folder for it. $values is the value that will be added to the file and FILE_APPEND says to add the line at the end of the file.

0

You can do this with the javascript:

var myJSON = JSON.stringify($("#id_do_meu_form").serializeArray());

The content will be in the variable myJSON, just use it any way you like.

  • It will not be possible to store in a file using Javascript and the data would be lost from one session to another. If you want to keep the answer, I believe you could make it complete by giving a solution to persist the data.

  • then there is no way to create a separate json file with this data?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.