How do I maintain text layout when using file_get_contents?
Let's say I have the following text file:
- This is the first line of the text file.
- This is the second line,
- 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:
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(...));
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:
- Write your page in pure HTML. Make it work as desired. Ask HTML questions if any.
- 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");
精彩评论