使用下面的脚本,我将帖子数据保存在 json 文件中,以这种形式保存:
{"name":"Bot","email":"bot@bot.ru"}
每次点击提交按钮,json文件中的数据都会简单的添加如下:
{"name":"Bot","email":"bot@bot.ru"}{"name":"Bot","email":"bot@bot.ru"}{"name":"Bot","email":"bot@bot.ru"}
如何使数据继续保存到有效的 json 文件中,遵循以下模式:
[{"name":"Bot","email":"bot@bot.ru"},{"name":"Bot2","email":"bot2@bot2.ru"}]
表格代码:
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$arr = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
$json_string = json_encode($arr);
file_put_contents($file, $json_string, FILE_APPEND);
// echo $json_string;
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<div style="text-align: center;">
<h1>Form</h1>
<form name="form1" method="post" action="">
<p>
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Your full name" autofocus required>
</p>
<p>
<label for="email">Email: </label>
<input type="email" name="email" id="email">
</p>
<p style="text-align: center;">
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
</div>
</body>
</html>
谢谢!
向上。
我使用 file_get_contents 和 str_replace 函数实现了所需的格式,但不知何故它都是歪的(((
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$arr = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
$json_string = json_encode($arr);
file_put_contents($file, '['.$json_string.']', FILE_APPEND);
}
// Если включены строгие типы, то есть объявлено (strict_types=1);
$file = file_get_contents('data.json', true);
$file = str_replace('][', ',', $file);
echo $file;
?>
想到的只有两种方法:
','.$json_string.']'。尝试在网上搜索关于json文件作为数据库的知识。您还可以使用 sqlLite 数据库,这也是一个文件,开箱即用的 php 可以使用它。如果json不重要,那么也可以用csv文件替换存储方式。
像这样的东西。如果之前没有写入数据,您可能需要创建一个新文件。