如何使用php添加到.json文件?目前,我正在使用php附加.json文件,但它不会将数据添加到现有的json对象。它创造了一个新的对象。我需要将所有数据存储在一个对象中,在外部JSON文件中。基本上,我有一个json对象,并希望为它添加更多的值。
由于
当前代码
<?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);
}
?>
答案 0 :(得分:13)
您可以将json文件解码为php数组,然后插入新数据并再次保存。
<?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
答案 1 :(得分:2)
上面提出的建议是艰难的。我正在考虑应该有一个更简单的方法,将数组附加到json文件中。
这是算法:
$handle=fopen($jsonFile);
fseek($handle,-1,SEEK_END);
fwrite($handle,$arrayToAdd);
fclose($handle);
但是我不确定这样做会比将整个json文件读入内存,添加数组然后存储它更有效。