【问题标题】:Load and update a locally JSON file by input text通过输入文本加载和更新本地 JSON 文件
【发布时间】:2015-04-29 19:51:41
【问题描述】:

我正在开发一个带有小型 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 可能是更好的解决方案,但我是从客户那里收到的。

【问题讨论】:

标签: javascript php json file


【解决方案1】:

尝试类似:

// 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));

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2012-05-16
    • 1970-01-01
    • 2017-05-08
    • 2021-05-31
    相关资源
    最近更新 更多