1

Currently, this is my code

$str = file_get_contents($sFile);
echo nl2br(htmlentities($str));

How can I keep the whitespace (tab and multiple spaces) in the files when i output them?

Example Input:

if(a==b){
  code   
    more code 
}

Should ouput exactly that (with htmlentities applied), but currently outputs

if(a==b){
code
more code
}

How can I keep whitespace?

mcky
  • 823
  • 2
  • 7
  • 20
  • The browser will automatically collapse/convert the whitespace characters into a single space. You can wrap the text in a
     element
    –  May 02 '16 at 04:09

2 Answers2

2

Wrap the output in <pre>...</pre> tags:

<pre>
if(a==b){
  code   
    more code 
}
</pre>

Browsers ignore superfluous whitespace, so you have to tell it not to ignore it.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
0

You can use html entity for space to keep the space:

echo str_replace([' ', "\t"], ['&nbsp;', '&nbsp;&nbsp;'], nl2br(htmlentities($str)));

Rauli Rajande
  • 2,010
  • 1
  • 20
  • 24