在浏览器中打开文本文件

时间:2019-04-27 18:17:57

标签: php

我使用以下命令在浏览器中显示文本文件:

echo file_get_contents($filename);

但是此命令连续显示消息的行。我想显示文章的行,例如一个单独的文本文件。您有什么解决办法?

2 个答案:

答案 0 :(得分:3)

您可以使用nl2br在字符串中的所有换行符之前插入HTML换行符。

  

nl2br(字符串$ string [,bool $ is_xhtml = TRUE]):字符串

     

返回在所有换行符(<br /><br>\r\n\n\r之前插入\n\r的字符串。

用法:

$content = file_get_contents($filename);
echo nl2br($content);

答案 1 :(得分:0)

仅使用file_get_contents会在您的浏览器中正确输出文件为文本,问题是您的浏览器会将其解释为html。在html中,多个空格被“合并”,因此您的文件显示为连续列表。

您必须在这里:

  • 向您的浏览器说您将给他文本(在响应中添加标题)
header('Content-Type:text/plain');
echo file_get_contents($filename);
  • 将文本转换为正确显示为html
$text = file_get_contents($filename);
echo "<pre>".htmlEntities($text)."</pre>";
相关问题