phpfile-get-contentshtml-entitiesnl2br

Keep white space with htmlentities


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?


Solution

  • 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.