开发者

Correct way of outputting a large block of HTML in PHP

开发者 https://www.devze.com 2023-01-27 10:17 出处:网络
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, a

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.


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


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();
    }

?> 


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.


Use

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

精彩评论

暂无评论...
验证码 换一张
取 消