0

我正在尝试制作一个简单的日记网站,在其中将文本输入文本区域,然后推送提交,它将显示在我当前的屏幕上。然后我希望能够在我的文本区域中输入更多文本,当我推送提交时,它只会在新行上显示给我。当我提交 3 个字符串 test、test1 和 test2 时,我得到以下信息。

Yes the test still works This is a test the test was successful This is a test

我想要这个输出

This is a test
the test was successful
Yes the test still works

这是我的 php

<?php
$msg = $_POST["msg"];
$posts = file_get_contents("posts.txt");
chmod("posts.txt", 0777);
$posts = "$msg\r\n" . $posts;
file_put_contents("posts.txt", $posts, FILE_APPEND);
echo $posts;
?>
4

1 回答 1

0

尝试添加 echo nl2br($posts); 反而。HTML 无法识别换行符。

建议从文件中删除最后一个 \r\n 或执行以下操作以摆脱底部的流氓行:

// take off the last two characters
$posts = substr($posts, 0, -2));

// convert the newlines
$posts = nl2br($posts);

// output
echo $posts;

要解决错误帖子问题:

// get the message
$msg = $_POST["msg"];

// store the original posts from the file
$original_posts = file_get_contents("posts.txt");

// set permissions (this isn't really required)
chmod("posts.txt", 0777);

// prepend the message to the whole file of posts
$posts = "$msg\r\n" . $original_posts;

// output everything
echo nl2br($posts);

// write the entire file (no prepend) to the text file
file_put_contents("posts.txt", $posts);
于 2013-12-06T00:13:46.247 回答