How to add to json array in .json file with php

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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); } ?> 

回答1:

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 


回答2:

what's suggested above is the hard way. i am considering there should be an easier way, to literally append an array into the json file.

here is the algo:

$handle=fopen($jsonFile); fseek($handle,-1,SEEK_END); fwrite($handle,$arrayToAdd); fclose($handle); 

but i am not sure it's more cpu/memory efficient to do so than reading the whole json file into memory, adding the array and then getting it stored.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!