php - 需要帮助使用 PHP 编写和读取文件
问题描述
因此,对于一项任务,我必须创建一个表单,用户可以在其中发布骑行分享,以便其他人可以看到并加入他们的骑行。我通过将表单写入文件 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
假设那里有多个帖子,它会将它们全部打印在一起。我需要一种方法来分隔帖子,以便我可以在板上很好地显示它们。
解决方案
使用多维数组。
$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);
推荐阅读
- r - rJava 在 shell 中加载和执行,但不在 cron 中
- android - Flutter项目添加华为agconnect后构建失败
- react-native - React Native)在字符串中连接变量(或JSX元素)
- java - 在spring-weblux中使用WebClient发送请求时如何从reactor netty管道中删除HttpClientCodec处理程序(默认添加)
- python - Python for 循环不会检查每个字符串是否为空
- r - 根据多个标准将数据框中的 NA 替换为第二个数据框中的值
- java - 华为广告,onAdClosed 不叫
- glsl - Instagram 上的 Shader 看起来与 SparkAR Studio 中的完全不同
- reactjs - 您正在一个已经运行 ES 模块构建的页面上加载 React Router 的 CommonJS 构建,所以事情不会正常工作
- java - 通过聚合键将映射映射到单个映射