I'm struggling on how to properly create a JSON file and append data to it, here's my PHP code:
<?php
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
$array = json_decode($jsonStr, true);
if ($array != null) {
$arrNew['ObjID']++;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$arrNew = [];
$array['ObjID'] = 0;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
If I refresh the URL in my browser by calling my php file, I get this output if i go to example.com/_users.json
{
"0": [],
"1": {
"ObjID": 1,
"username": "bob",
"email": "b@doe.com"
},
"2": {
"ObjID": 1,
"username": "sarah",
"email": "b@doe.com"
},
"3": {
"ObjID": 1,
"username": "sarah",
"email": "b@doe.com"
},
"ObjID": 0,
"username": "bob",
"email": "b@doe.com"
}
So I'm able to generate a .json file, but what I need to do is a piece of code to do the following sequence:
- Since the first time I run the script, the _users.json file doesn't exist, it needs to get generated
- Create a JSON main object
- Insert 1st object inside the main object
- Append a 2nd object (still inside the main object)
- And so on with 3rd, 4th, etc..
So I would need to get an output like this:
{ <-- Main Object starts
"1": { <-- 1st object inside the Main Object
"ObjID": 1,
"username": "bob",
"email": "b@doe.com"
},
"2": { <-- 2nd object
"ObjID": 1,
"username": "sarah",
"email": "s@doe.com"
}
} <-- Main Object closes
I can't really figure out what I'm doing wrong in my PHP code.