Is there harm in outputting html vs. using echo?

前端 未结 4 1593
梦毁少年i
梦毁少年i 2020-12-21 11:13

I have no idea really how to say this, but I can demonstrate it:

Content Title\";
}
?>

相关标签:
4条回答
  • 2020-12-21 11:33

    There are no relevant differences performance-wise. But you won't be able to use variables in the latter, and it looks less clean IMO. With large blocks, it also becomes extremely difficult to keep track of {} structures.

    This is why the following alternative notation exists:

    <?php if (true): ?>
    <h1>Content Title</h1>
    <?php endif; ?>
    

    it's marginally more readable.

    0 讨论(0)
  • 2020-12-21 11:35

    I appreciate all the feedback. :)

    I did find out some issues when using the two different methods.

    There does not appear to be any real issue here except that the formatting looks terrible on the source and the tedious nature of it.

    <?php
    if (true) {
    echo "<h1>Content Title</h1>";
    }
    ?>
    

    Using php this way can cause an error as such Warning: Cannot modify header information - headers already sent

    <?php  if (true) {  ?>
    <h1>Content Title</h1>
    <?php  }  ?>
    

    The headers error can possibly be solved by using php like so

    <?php ob_start(); if (true) {  ?>
    <h1>Content Title</h1>
    <?php  }  ob_end_flush(); ?>
    

    As to why and when the headers are sent, I am not completely sure...

    0 讨论(0)
  • 2020-12-21 11:40

    There's a small difference between the two cases:

    <?php
    if (true) {
        echo "<h1>Content Title</h1>";
    }
    ?>
    

    Here, because you're using double quotes in your string, you can insert variables and have their values rendered. For example:

    <?php
    $mytitle = 'foo';
    if (true) {
        echo "<h1>$mytitle</h1>";
    }
    ?>
    

    Whereas in your second example, you'd have to have an echo enclosed in a php block:

    <?php  if (true) {  ?>
        <h1><?php echo 'My Title'; ?></h1>
    <?php  }  ?>
    

    Personally, I use the same format as your second example, with a bit of a twist:

    <?php if (true): ?>
        <h1><?php echo $mytitle; ?></h1>
    <?php endif; ?>
    

    I find that it increases readability, especially when you have nested control statements.

    0 讨论(0)
  • 2020-12-21 11:48

    This:

    <?php if (true) : ?>
        <h1>Content Title</h1>
    <?php endif; ?>
    

    This is the way PHP is supposed to be used.
    Don't echo HTML. It's tedious, especially because you have to escape certain characters.

    There may be slight performance differences, with the above probably being faster. But it shouldn't matter at all. Otherwise, no differences.

    0 讨论(0)
提交回复
热议问题