Search code examples
phphtmlspecialchars

Include Line Breaks with htmlspecialchars


I am creating a pattern library similar to A List Apart's here: http://patterns.alistapart.com/. I am using the following code snippet to grab the contents of the HTML file and output it on the page (see the code area on A List Apart's example):

echo "<code class=\"col-md-8 col-sm-6 prettyprint pattern-markup language-markup\">".htmlspecialchars(@file_get_contents($dir.'/'.$ff))."</code>\n";

It is pulling in the code, but is stripping out all line breaks in the HTML so the code all runs together. Is it possible to add the line breaks back into the code view? I know nl2br is an option, but that works if I was outputting the HTML in visual mode, not code.

Thanks!


Solution

  • This has absolutely nothing to do with stripping newlines and everything to do with how basic HTML works.

    Try this:

    <p>Hello
    
    
    
    
    
    World</p>
    

    Do you see newlines? Nope.

    Try applying the CSS white-space: pre-wrap to your element.