ntc ntc - 1 year ago 80
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.

if(something == somethingelse) {
echo "some message";
else {
<?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 Source

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:

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

        <!-- more HTML -->

<?php endif; ?>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download