开发者

How do I maintain text layout when using file_get_contents?

开发者 https://www.devze.com 2023-01-11 09:58 出处:网络
Let\'s say I have the following text file: This is the first line of the text file. This is the second line,

Let's say I have the following text file:

  1. This is the first line of the text file.
  2. This is the second line,
  3. and here goes the third.

When using

echo file_get_contents($_SERVER{'DOCUMENT_ROOT'} . "/file.txt");

The output is

This is the first line of the text file. Th开发者_Python百科is is the second line, and here goes the third.

How do I prevent the layout from changing?

Thanks in advance :-)


In HTML, new line characters (\n or \r\n) don't cause actual line breaks to appear in the rendered page. Here are two possible solutions:

  1. Use the nl2br() function to convert newlines to <BR> tags. This will work for some layouts, but not for ASCII art or others that rely on multiple spaces (which are reduced to one in HTML).

    echo nl2br(file_get_contents(...));
    
  2. Wrap the result in <pre> tags. This will keep all layout, but can look a bit ugly. You can style <pre> tags with CSS to make them prettier, if you'd prefer.

    echo '<pre>' . file_get_contents(...) . '</pre>';
    


Every time you are gonna use PHP, it must be done in 2 parts:

  1. Write your page in pure HTML. Make it work as desired. Ask HTML questions if any.
  2. Write a PHP script which produce the the same text.

An HTML tag that could help you is <pre>

Another way to tell to browser that here hoes plain text is to send appropriate HTTP header
So, it this text is the only text being displayed on this page,

header("Content-type: text/plain");
readfile($_SERVER['DOCUMENT_ROOT'] . "/file.txt");
0

精彩评论

暂无评论...
验证码 换一张
取 消