Add arrays in PHP JSON file

Asked

Viewed 155 times

0

Next, I need to make a json file with a stock of products and a page to add them to JSON. I got it with PHP through json_encode() add an array, but the problem: When I add an array, it n writes the comma to separate the items and does not write the opening and closing of the json. my code:

if (!empty($_GET)) {
var_dump($_GET); //Visualiza a variavel
$newProduct = array(
"nome" => $_GET["nome"],
"preco" => $_GET["preco"]);
$dados=$newProduct;
$dadosJSON = json_encode($dados);
$fp = fopen("contatos.json","a");
$escreve = fwrite($fp,$dadosJSON);
fclose($fp); }

How does it look:

{"nome":"Produto teste 1","preco":"9999"}{"nome":"Produto teste 2","preco":"99998"}

How it should look:

[{"nome":"Produto teste 1","preco":"9999"},{"nome":"Produto teste 2","preco":"99998"}]

If you can do it in JS without a problem... Some light?

1 answer

0

Hell, more time to understand the problem than to answer...

Anyway, you can’t go out saving, adding and concatenating the code like this, because sooner or later it ends up giving problems, you must adopt a pattern that will fit the system better, what needs an explanation / broader view of what it does and what you use it for, examples:

  • If you have control of the first and last insertion, you can open "[", add the items with "," before them and at the end add a "]".

  • You can choose to save a record in each row and at the time of reading, turn each row back to a record.

  • You can organize and standardize the items in the file and when sending, make a single conversion to json with json_encode().

  • You can try to use implode() and explode() to try to solve this problem.

Who will decide what fits best, or if no option fits, is you when analyzing the code and its goal.

Note: From a glance at the question formulation topics, sometimes help you organize / structure your topic and get help more easily.

Browser other questions tagged

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