我正在开发一个带有小型 CMS 系统的项目,其中数据从外部 JSON 文件加载。
此数据加载完美,但随后我尝试使用 HTML 输入字段更新 JSON(例如更改标题和内容)
JSON 文件的一些预览:
{
"title":"Homepage",
"paths": [{
"path": [{
"questions":"Home"
}]
}]
}
这是我用于加载的代码:
$string = "file.json";
$jsonString = file_get_contents($string);
$data = json_decode($jsonString, true);
$paths = $data["paths"];
然后有一些像这样的输入字段:
<input type="text" name="title" value="Update the title" />
所以我只想更新一些文本字段并覆盖 JSON 标题。希望可以有人帮帮我。
PS:我知道 SQL 可能是更好的解决方案,但我从客户那里收到了这个。
最佳答案
尝试如下:
// read the file like you did before
$string = "file.json";
$jsonString = file_get_contents($string);
$data = json_decode($jsonString, true);
// update whatever fields you need to
$data["title"] = $_POST["title"];
// json_encode() and write back to the same file you read from
file_put_contents($string, json_encode($data));
关于javascript - 通过输入文本加载和更新本地 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29953238/