Skip to content Skip to sidebar Skip to footer

Is There Harm In Outputting Html Vs. Using Echo?

I have no idea really how to say this, but I can demonstrate it: Content Title'; } ?> vs

Solution 1:

There's a small difference between the two cases:

<?phpif (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:

<?phpif (true) {  ?><h1><?phpecho'My Title'; ?></h1><?php  }  ?>

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

<?phpif (true): ?><h1><?phpecho$mytitle; ?></h1><?phpendif; ?>

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

Solution 2:

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:

<?phpif (true): ?><h1>Content Title</h1><?phpendif; ?>

it's marginally more readable.

Solution 3:

This:

<?phpif (true) : ?><h1>Content Title</h1><?phpendif; ?>

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.

Solution 4:

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.

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

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

<?phpif (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...

Post a Comment for "Is There Harm In Outputting Html Vs. Using Echo?"