我想编写php将信息添加到json id包中。 我希望它在同一区域。 对不起,我打的英文不好。我使用翻译。
我的代码:-
<?php
$donatename = $_POST['donatename'];
$donateURL = $_POST['donateurl'];
$json1_str = '{
"transaction": "'.$fti_u.'",
"donatename": "'.$donatename.'",
"donateURL": "'.$donateURL.'",
"releaseddate": "'.$fttime_u.'"
}';
$json1 = json_decode($json1_str, true);
$json2['packages'][] = $json1;
$jsonData = json_encode($json2, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents('data.json', $jsonData, FILE_APPEND);
?>
---我目前正在得到的输出---
{
"packages": [
{
"transaction": "",
"donatename": "",
"donateURL": "",
"releaseddate": ""
}
]
}{
"packages": [
{
"transaction": "",
"donatename": "",
"donateURL": "",
"releaseddate": ""
}
]
}
----预期-----
{
"packages": [
{
"transaction": "",
"donatename": "",
"donateURL": "",
"releaseddate": ""
},
{
"transaction": "",
"donatename": "",
"donateURL": "",
"releaseddate": ""
}
, {
"transaction": "",
"donatename": "",
"donateURL": "",
"releaseddate": ""
}
]
}
错误:
第10行的解析错误:...“”}]} {“ packages”:[ -------------------- ^预期为'EOF','}',',',']'
答案 0 :(得分:0)
您想将数据添加到现有内容中,因此只需读取现有数据文件,添加新内容,然后使用新版本的数据覆盖现有文件...
$json1 = json_decode($json1_str, true);
// Load existing content
$json2 = json_decode(file_get_contents('data.json'), true);
$json2['packages'][] = $json1;
$jsonData = json_encode($json2, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents('data.json', $jsonData); // Remove the append