[英]How to write new nodes to json file on server using php
How can i handle an array sent by jquery to put into an existing nested json file with php? 我该如何处理由jQuery发送的数组以使用php将其放入现有的嵌套json文件中? I can send the data with jquery but all i can manage is php overwriting the file or adding the data to the end of the document, i need to put new data in the nested structure of the json file.
我可以使用jquery发送数据,但我所能管理的只是php覆盖文件或将数据添加到文档的末尾,我需要将新数据放入json文件的嵌套结构中。
My script looks like this; 我的脚本看起来像这样;
<?php
$postdata = $_POST['data'];
$postdata = json_encode($postdata);
file_put_contents('json/user.json', $postdata);
?>
My json had a nested structure like; 我的json具有类似的嵌套结构;
"{\"users\":
[{\"user\":
[{\"id\":\"martijn\",
\"pw\":\"password\",
\"name\":\"user3\",
\"icons\":
[{\"bookmarks\":\"bookmark3\",
\"notes\":\"note3\"
}]
}]
}]
}"
I would like to add another user to the users, how would i do that with php? 我想向用户添加另一个用户,我将如何用php做到这一点?
My jQuery request and the data to send; 我的jQuery请求和要发送的数据;
var newUser = [{
user: [{
id: username,
pw: password,
name: "user3",
icons: [{
bookmarks: "bookmark3",
notes: "note3"
}]
}]
}];
var userSetup = JSON.stringify(newUser);
$.ajax({
url: themeUrl + '/script.php',
type: 'POST',
data: {
data: newUser,
},
dataType: 'json'
});
This a bit tricky situation, 这有点棘手,
You need to make use of these steps inorder to do that.. 您需要利用这些步骤才能做到这一点。
user.json
exists by using file_exists()
file_exists()
检查user.json
文件user.json
存在 file_get_contents()
file_get_contents()
从中读取所有内容 json_decode()
it and store that in an array. json_decode()
并将其存储在数组中。 $_POST['data']
and add it to the earlier decoded array. $_POST['data']
并将其添加到较早的解码数组中。 json_encode()
it to a string. json_encode()
转换为字符串。 user.json
file using file_put_contents()
. file_put_contents()
user.json
文件。 [No need of the FILE_APPEND
flag] FILE_APPEND
标志] The coding part... 编码部分...
<?php
if(file_exists('json/user.json'))
{
$cont = file_get_contents('json/user.json');
$usr_array = json_decode($cont,1);
foreach($_POST['data'] as $val)
{
$usr_array[]=$val;
}
$newData = json_encode($usr_array);
file_put_contents('json/user.json', $newData );
}
else
{
die('File does not exist !');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.