0

I'm adding my HTML to a var:

$html = '';
$html .= '<li>';
$html .= '<p>hello</p>';
$html .= '</li>';
....
echo $html

When I view the page's source the above is all output on one line. How can I fix it so that we see the layout as you would if it was written:

<ul>
    <li>
        <p>hello</p>
    </li>
    ...
panthro
  • 22,779
  • 66
  • 183
  • 324
  • 1
    You would add the spaces/tabs yourself, does it really matter if the output is indented? - Browsers don't care. – Alex K. Sep 12 '16 at 15:24

4 Answers4

2

Could always do this:

?>
<ul>
    <li>
        <p>hello</p>
    </li>
</ul>
<?php

BUT keep in mind that there is an important difference between "all mashed together" and "nicely spaced out": whitespace will cause empty text nodes to be added, which may interfere with layouts (if using display:inline-block) or JavaScript (if using childNodes). It also takes up extra unnecessary bandwidth. Use what is most appropriate.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Add newlines with \n and tabs with \t:

$html = '';
$html .= "<li>\n";
$html .= "\t<p>hello</p>\n";
$html .= "</li>\n";
j08691
  • 204,283
  • 31
  • 260
  • 272
  • If you're going to store this string in a file then it's better to use `PHP_EOL` rather than `\n` otherwise `\n` is better. – apokryfos Sep 12 '16 at 15:44
1

You can add all at once:

$html = '
<ul>
    <li>
        <p>hello</p>
    </li>
</ul>
';
ban17
  • 634
  • 8
  • 12
0

Try using the PHP constant PHP_EOL.

$html = '';
$html .= '<li>' . PHP_EOL;
$html .= '<p>hello</p>' . PHP_EOL;
$html .= '</li>' . PHP_EOL;
BA_Webimax
  • 2,714
  • 1
  • 13
  • 15