I have a simple functionality for adding products in JS and I am trying to save this products to a .json file using php.
My json objects in JS look like :
{id: 1474791226069, name: "prod", brand: "yhh", price: "2"}
And my php for saving them in my .json file is the following:
<?php
$data[] = $_GET['data'];
$inp = file_get_contents('products.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
var_dump($jsonData);
file_put_contents('products.json', $jsonData);
?>
Sadly, the result I get in my .json file looks a bit weird :
[["{"id":1474721566304,"name":"GGG","brand":"GG","price":"3"}"],["{"id":1474721570904,"name":"GGGH","brand":"GGH","price":"4"}"],["{"id":1474721574188,"name":"GGGH","brand":"GGHH","price":"5"}"]]
I’ve found it imposible to, let’s say, look for a product by ID and delete or update it. I know a .json file is not supposed to look like this, so my question is : How to make my .json file to look like a normal .json and still to be able to append new .json records from my JS, aka this:
[
{"id":1,"product":"one", "brand":"blah","price":"1"},
{"id":2,"product":"two", "brand":"blah","price":"2"},
{"id":3,"product":"three", "brand":"blah","price":"3"}
]
So I can be able to add new records, and decode/encode it in a more conventional way?
Please help!
Advertisement
Answer
From your comment,
$_GET[‘data’] is shown in the question, it is a json object like this {id: 1474791226069, name: “prod”, brand: “yhh”, price: “2”}
When decoding a json object, always pass the second parameter as true
to convert the objects into associative arrays. Also, you have to use an additional array, for example, $resultData
to achieve the desired result. So the solution would be like this:
$resultData = $tempArray = array();
$data = json_decode($_GET['data'], true);
if(($inp = file_get_contents('products.json')) != false){
$tempArray = json_decode($inp, true);
}
array_push($tempArray, $data);
$resultData[] = $tempArray;
$jsonData = json_encode($tempArray);
file_put_contents('products.json', $jsonData);
var_dump($jsonData);