How do I add to a .json file with php? Currently, I'm appending a .json file with php, but it won't add the data to an existing json object. It makes a new object. I need the data all stored in one object, in an external JSON file. Basically, I have a json object and want to add more values to it.
Thanks
Current Code
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql="SELECT * FROM accounts WHERE uname = '$username' AND pword = '$password'";
$r = mysql_query($sql);
$name = "";
while($row = mysql_fetch_array($r))
{
$name = $row["name"];
$lat = $row["lat"];
$lon = $row["lon"];
$it = $row["it"];
}
if(mysql_num_rows($r) != 1){
echo json_encode(array("message" => "Nope! Wrong Login!"));
}
if(mysql_num_rows($r) == 1)
{
$jsonFile = "test.json";
$fh = fopen($jsonFile, 'w');
$json = json_encode(array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it));
fwrite($fh, $json);
echo json_encode($json);
}
?>
json_decode
it,array_merge
it with the new array, and thenjson_encode
it again. – Waleed Khan Mar 1 at 2:18