Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
}
?>
share|improve this question
6  
I would json_decode it, array_merge it with the new array, and then json_encode it again. – Waleed Khan Mar 1 at 2:18
Your saying to retrieve whats already there, then merge and re-encode the arrays? Then, re write it to the json file? – copilot0910 Mar 1 at 2:23
Precisely. I am not aware of any feasible in-place transformation that you might use. – Waleed Khan Mar 1 at 2:27
As long as the data gets merged, I'm ok. – copilot0910 Mar 1 at 2:27
I've to say that mysql functions are absolete, use PDO or mysqli functions instead. – DBPBTPV Mar 1 at 2:32

1 Answer

up vote 1 down vote accepted

You can decode the json file to a php array, then insert new data and save it again.

<?php
$file = file_get_contents('data.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[] = array('data'=>'some data');
//save the file
file_put_contents('data.json',json_encode($data));
unset($data);//release memory
share|improve this answer
exactly what I needed. Thank you very much – copilot0910 Mar 1 at 2:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.