Skip to content
Advertisement

Properly writing multiple json records to a JSON file using PHP

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 :

JavaScript

And my php for saving them in my .json file is the following:

JavaScript

Sadly, the result I get in my .json file looks a bit weird :

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement