我有一个简单的html表单,调用php脚本来创建或更新包含json脚本的文件。
我的html代码
<form name="inputs" method="post" action="parameters.php">
Provide template name: <input type="text" name="templatename"><br>
Which type? <select name="type"> <option value="abc">abc</option> <option value="def">def</option> <option value="ghi">ghi</option> </select><br>
What name? <input type="text" name="name"><br>
<input type="submit" name="Submit" value="submit">
</form>
这是parameters.php,
<?php
class Templates {
public $templatename = "";
public $type = "";
public $name = "";
}
$mytemplate = new Templates();
$mytemplate->templatename = $_POST['templatename'];
$mytemplate->type = $_POST['type'];
$mytemplate->name = $_POST['name'];
$data = json_encode($mytemplate);
$templates = file_get_contents('users.txt');
$templates = json_decode($templates);
array_push($templates, $data);
$fh = fopen("users.txt", "a");
fwrite($fh, $templates);
fclose($fh);
?>
这给了我以下输出,
{"templatename":"1","type":"abc","name":"abc123"}{"templatename":"2","type":"def","name":"def123"}
生成的json语法错误。我如何添加一个新的json元素到预先存在的json元素,我如何添加一个新的json元素时,没有以前的json元素?
您需要将文件中已经存在的信息读入内存(json_decode()
it),然后将新对象添加到对象数组(json_encode()
it)中,并覆盖该文件。
在本例中,您的数据结构可能是一个对象数组。
目前,您的代码只尝试将一系列JSON编码的对象添加到文件中,使其在整个文件中没有有效的JSON。
我想说,如果你希望你的JSON表示显著增长,这是一个相当低效的方式来处理这个问题。您可能需要考虑另一种类型的持久性。