Preserve linebreak txt php

廉价感情. 提交于 2019-12-30 05:14:07

问题


How can I read a .txt file from my server, and preserve it's linebreaks? Note that the linebreaks aren't like this /n or something, they are more like

this. You know, just a new line in plain text.

I would like to echo the .txt file from my server, this is in PHP or something, while preserving the linebreaks.

Thanks a heck in advance ! :)


回答1:


For output? Just use nl2br

$file = file_get_contents( 'file.txt' );
echo nl2br( $file );

Also works with fopen.




回答2:


The line breaks are preserved without you needing to do anything. You can easily verify this by running the code from the command line, for example with

php -r "readfile('text.txt');"

However, in HTML whitespace is collapsed by default. If you want to preserve it use the CSS white-space attribute like this:

<div style="white-space: pre"><?php readfile('text.txt'); ?></div>


来源:https://stackoverflow.com/questions/14269017/preserve-linebreak-txt-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!