Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to format long strings of HTML in PHP?

I know it's really a subjective question, but for best-practices (and readability), I can't seem to get a fix on the best way to format long strings of HTML. I typically do it like this:

echo '
<div>
    <p>Content Inside</p>
    <div class="subbox">
        <ul>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
            <li>etc.</li>
        </ul>
    </div>
</div>
';

But I still don't like the outcome, especially if this appears in the middle of a large block of code. It just feels messy.

like image 832
dclowd9901 Avatar asked Nov 30 '22 10:11

dclowd9901


1 Answers

You can jump out of PHP and input HTML directly:

<?php $var = "foo"; ?>
<div>
  <ul>
    <li>Foo</li>
  </ul>
</div>
<?php $foo = "var"; ?>

If all you're doing is an echo/print, I think this is much cleaner. Furthermore, you don't need to run through and escape single/double quotes within the HTML itself.

If you need to store the HTML in a variable, you could use HEREDOC:

$str = <<<EOD
<div>
  <ul>
    <li>Foo</li>
  </ul>
</div>
EOD;
like image 182
Sampson Avatar answered Dec 10 '22 19:12

Sampson