cop*_*910 1 php arrays json file
如何用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);
}
?>
Run Code Online (Sandbox Code Playgroud)
Lic*_*son 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16330 次 |
| 最近记录: |