php 有没有办法将纯文本转换为带有换行符的 HTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9345514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any way to convert plain text into HTML with line breaks?
提问by Chrispy
I have a PHP script which retrieves the contents of a raw / plain-text file and I'd like to output this raw text in HTML, however when it's outputted in HTML all the line breaks don't exist anymore. Is there some sort of PHP function or some other workaround that will make this possible?
我有一个 PHP 脚本,它检索原始/纯文本文件的内容,我想以 HTML 格式输出此原始文本,但是当它以 HTML 格式输出时,所有换行符都不再存在。是否有某种 PHP 函数或其他一些解决方法可以使这成为可能?
For example, if the raw text file had this text:
例如,如果原始文本文件有以下文本:
hello
my name is
你好,
我的名字是
When outputted in HTML, it will say:
当以 HTML 输出时,它会说:
hello my name is
你好我的名字是
Is there any way to preserve these line breaks in HTML? Thank you.
有没有办法在 HTML 中保留这些换行符?谢谢你。
(If it helps, my script gets the contents of the raw text file, puts it inside a variable, and I just echo out the variable.)
(如果有帮助,我的脚本会获取原始文本文件的内容,将其放入一个变量中,然后我只回显该变量。)
回答by Zar
回答by Vyktor
There are several ways to do this:
做这件事有很多种方法:
Using file_get_contents()
and nl2br()
:
使用file_get_contents()
和nl2br()
:
echo nl2br( file_get_contents( 'filename.txt'));
This won't solve special entities like <>&
, you'll need to use htmlspecialchars()
这不会解决像 那样的特殊实体<>&
,您需要使用htmlspecialchars()
echo nl2br( htmlspecialchars( file_get_contents( 'filename.txt')));
Perhaps better solution would be loading entire file into array with file()
and iterate trough all elements (you'll be able to put lines into table or so in future)
也许更好的解决方案是将整个文件加载到数组中file()
并遍历所有元素(将来您可以将行放入表中)
$data = file( 'filename.txt');
foreach( $data as $line){
echo htmlspecialchars( $line) . '<br />';
}
And if you need to process large amount of data it'd be best to do it sequentially with fopen()
and fgets()
:
如果您需要处理大量数据,最好使用fopen()
和依次执行fgets()
:
$fp = fopen( 'filename.txt', 'r') or die( 'Cannot open file');
while( $line = fgets( $fp)){
echo htmlspecialchars( $line) . '<br />';
}
fclose( $fp);
回答by czupe
In html code you can use. <br/>
Read this function http://php.net/manual/en/function.nl2br.phpIt will help;)
在 html 代码中,您可以使用。<br/>
阅读此功能http://php.net/manual/en/function.nl2br.php它将有所帮助;)