如何读取带有空格和行短行的txt文件[重复]

问题描述 投票:-1回答:1

此问题已经在这里有了答案:

我有一个平面文件database-001.txt文件,其中包含条目。我的txt文件如下所示:

Bill

message Bill goes here
1571436403

==
John

message John goes here
1571436126

==
Earl

message earl goes here 
1571436051

==


为了读取.txt文件,我使用此代码:

$flatfile = file_get_contents('database-001.txt');
echo $flatfile;
?>

但是像这样使用它,会产生这个:

Bill message Bill goes here 1571436403==Johnmessage John goes here1571436126==Earlmessage earl goeshere 1571436051==

如何读取与.txt文件中的内容完全相同的换行符和白线?

php file-get-contents
1个回答
-1
投票

尝试:

$flatfile = file_get_contents('database-001.txt');
echo nl2br($flatfile);

发生的情况是,浏览器无法理解\n。您应该改用<br>nl2br将所有经典的新行\n转换为<br>

您可以通过以下示例轻松看到它:

$str1 = "regular \n newline";
$str2 = "browser <br> newline";
echo str1;
echo str2;

尝试在浏览器中一次在控制台中运行上述4行。

© www.soinside.com 2019 - 2024. All rights reserved.