如何添加到JSON数组与PHP以.json文件 [英] How to add to json array in .json file with php
本文介绍了如何添加到JSON数组与PHP以.json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何添加使用PHP一个以.json文件?目前,我追加到PHP的以.json文件,但它不会将数据添加到现有的JSON对象。它使一个新的对象。我需要所有存储在一个对象中的数据,在外部JSON文件。基本上,我有一个JSON对象,并希望更多的价值添加到它。
感谢
当前code
< PHP$用户名= mysql_real_escape_string($ _ POST ['用户名']);
$密码= mysql_real_escape_string($ _ POST ['密码']);$ SQL =SELECT * FROM户口所在的uname ='$的用户名'AND PWORD ='$的密码';$ R =的mysql_query($的SQL);$ NAME =;而($行= mysql_fetch_array($ R))
{
$名称= $行[名称];
$纬度= $行[纬度];
$ LON = $行[LON];
$它= $行[它];
}如果(mysql_num_rows($ R)!= 1){
回声json_en code(阵列(信息=>没有错误的登录!));
}
如果(mysql_num_rows($ R)== 1)
{ $ jsonFile =test.json;
$跳频=的fopen($ jsonFile,'W'); $ JSON = json_en code(阵列(信息=> $名字,纬度=>纬度$,经度=> $ LON,它=> $吧)); FWRITE($ FH,$ JSON); 回声json_en code($ JSON);
}
?>
解决方案
您可以去code JSON文件到一个PHP数组,然后插入新的数据并再次保存它。
< PHP
$文件=的file_get_contents('data.json');
$数据= json_de code($文件);
未设置($文件);对于大型JSON // prevent内存泄漏。
//此处插入数据
$数据[] =阵列('数据'=>'一些数据');
//保存文件
的file_put_contents('data.json',json_en code($数据));
未设置($数据); //释放内存
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);
}
?>
解决方案
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
这篇关于如何添加到JSON数组与PHP以.json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文