因此,对于一项作业,我必须创建一个表单,用户可以在其中发布乘车份额,以便其他人可以看到并加入他们的乘车。为此,我将表单写入data.txt文件,然后读取文件以在板上显示所有游乐设施。我唯一的问题是,当我获得data.txt的内容时,它们全部组合在一起。我需要能够分别显示每个游乐设施。我将如何去做呢?
到目前为止,这是我的代码: 写作:
if (isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['date'])
&& isset($_POST['destination'])
&& isset($_POST['msg'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$destination = $_POST['destination'];
$msg = $_POST['msg'];
//TODO the file write here VV, use 'a' instead of 'w' too ADD to the file instead of REWRITING IT.
$arr = [$name,$email,$date,$destination,$msg];
$write = json_encode($arr);
$file = fopen('data.txt', 'a');
fwrite($file, $write);
fclose($file);
}
阅读内容:
$path = 'data.txt';
$handle = fopen($path, 'r');
$contents = fread($handle, filesize($path));
echo $contents;
fclose($handle);
$newarr = [json_decode($contents)];
foreach($newarr as $stuff)
{
echo $stuff[0];
}
输出类似于:
["Simon Long","example@gmail.com","2109-01-01T01:01","canada","this is a message"] Simon Long
假设其中有多个帖子,它只会将它们全部打印在一起。我需要一种分隔帖子的方法,以便可以在板上很好地显示它们。
答案 0 :(得分:1)
使用多维数组。
$arr = [
"Simon Long","example@gmail.com","2109-01-01T01:01","canada","this is a message",
"John Doe","john@gmail.com","2109-01-01T01:01","canada","this is a message",
"Jane Doe","jane@gmail.com","2109-01-01T01:01","canada","this is a message"
];
然后,当您添加到它时,只需追加到最终数组并替换整个文件即可。
$contents = file_get_contents($path);
$decoded = json_decode($contents);
$decoded[] = [$name,$email,$date,$destination,$msg];
file_put_contents($path, json_encode($decoded)); //replace the entire file.
也请注意。 isset
接受多个参数,因此您无需按原样使用它。您可以这样做:
if (isset($_POST['name'], $_POST['email'], $_POST['date'], $_POST['destination'] ...)
清理来自用户的任何输入也是一个好主意。
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);