首页 > 解决方案 > 需要帮助使用 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

假设那里有多个帖子,它会将它们全部打印在一起。我需要一种方法来分隔帖子,以便我可以在板上很好地显示它们。

标签: phpatom-editor

解决方案


使用多维数组。

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


推荐阅读