ntc ntc - 5 days ago 7
PHP Question

Correct way of outputting a large block of HTML in PHP

I am learning PHP (no programming experience) from a book. The examples in the book use a strange way of outputting a large block of HTML conditionally. It closes the PHP tag inside the conditional, and reopens it after outputting the HTML. I understand (after some head scratching) how it works, but it seems like a dodgy, not-intended-to-be-used-like-this, workaround.

<?php
if(something == somethingelse) {
echo "some message";
}
else {
?>
<big-block-of-html>
</big-block-of-html>
<?php }
?>


The book did introduce the heredoc syntax, but never used it. Is there a right way of doing this? It would seem more intuitive to output the HTML from within PHP.

Answer

That's exactly how PHP is supposed to be used and is much more readable, elegant and robust than all alternatives*. I'd just go for a better indented style:

<?php
    // normal
    // code
    // here
?>
<?php if ($foo) : ?>

    <div>
        <!-- more HTML -->
    </div>

<?php endif; ?>

* Unless you go for completely code-free templates like Smarty of course...

Comments