ntc
ntc

Reputation: 257

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.

Upvotes: 9

Views: 15333

Answers (4)

benhowdle89
benhowdle89

Reputation: 37504

Use

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

Upvotes: -1

deceze
deceze

Reputation: 522530

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...

Upvotes: 14

Svisstack
Svisstack

Reputation: 16656

Think about hide this block in other file. Then you can create some function like this:

function get_some_big_block_content()
{
    return get_file_contents('./your_big_block.html');
}

Then you can:

<?php 
    if(something == somethingelse) { 
        echo "some message";
    } 
     else { 
        echo get_some_big_block_content();
    }

?> 

Upvotes: 1

Piskvor left the building
Piskvor left the building

Reputation: 92792

PHP allows multiple ways of doing this; picking one is mostly a matter of preference - for some, this is the most readable option, for some it's a horrible hack.

In all, inline HTML is hard to maintain in any form - if you're putting any serious effort into your website, consider some sort of templating system (e.g. Smarty) and/or framework (e.g. Symfony), otherwise you'll go mad from trying to maintain the PHP+HTML soup.

Upvotes: 0

Related Questions