gpt4 book ai didi

php - 使用 PHP 将数据附加到 .JSON 文件

转载 作者:行者123 更新时间:2023-12-02 22:50:12 24 4
gpt4 key购买 nike

我有这个 .json 文件:

[
{
"id": 1,
"title": "Ben\\'s First Blog Post",
"content": "This is the content"
},
{
"id": 2,
"title": "Ben\\'s Second Blog Post",
"content": "This is the content"
}
]

这是我的 PHP 代码:

<?php
$data[] = $_POST['data'];

$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);

问题是,我不太确定如何实现它。每次提交表单时,我都会调用上面的代码,因此我需要递增 ID,并使用 [{ 保持有效的 JSON 结构,这可能吗?

最佳答案

$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);

关于php - 使用 PHP 将数据附加到 .JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com