javascript - 通过输入文本加载和更新本地 JSON 文件

标签 javascript php json file

我正在开发一个带有小型 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/

相关文章:

javascript - 加载时的 Bootstrap-angular-ui 模式

php - CSV 数据库输入导致每列占一行

php - .htaccess 重定向文件类型

android - JSON 解析成 ListView

c++ - 如何修复 ZeroMQ 发布者 C++ 中的运行时错误

javascript - D3 : refining ordinal scale to return groups of colours?

javascript - 使用大量内容可编辑 div 时 Angular 6/Ionic 4 PWA 性能下降

javascript - 使用 AJAX 更新从数据库(mysql)检索的数据

json - MongoDB 查询语言本身是否有 JSON 模式之类的东西?

javascript - 当尺寸改变时平滑地向上或向下滑动