如何在.json文件中添加到JSON数组 [英] How to add to JSON array in .json file

查看:412
本文介绍了如何在.json文件中添加到JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PHP添加到.json文件?目前,我正在使用PHP附加.json文件,但不会将数据添加到现有的JSON对象中。它成为一个新对象。我需要将所有数据都存储在一个外部JSON文件中的一个对象中。基本上,我有一个JSON对象,想向它添加更多值。

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.

$jsonFile = "test.json";
$fh = fopen($jsonFile, 'w');

$json = json_encode(array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it));

fwrite($fh, $json);


推荐答案

您可以将json文件解码为php数组,然后插入新数据并再次保存。

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文件中添加到JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆