In terms of performance , what would be better. Using PHP to echo all the HTML output so I can pepper it with the various bits of working code and variables or escape HTML t
Code as if the next programmer taking over the project is a serial killer. In other words, use the second option you mentionned.
Whichever is easiest to read.
The performance difference is pretty negligible compared to almost any other issue you'll encounter. Definitely readability is hands down the first issue here.
It's all about which you find the most readable. Of course, this will vary with each situation. If you were doing an entire page, and there were large sections which did not have any PHP in it, then I'd break out of PHP and just write the plain HTML, whereas if there was a section which had a lot of PHP variables, I'd do it all in PHP.
For example:
<table>
<tr>
<td colspan="<?php echo $numCols; ?>">
<?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
</td>
</tr>
</table>
versus:
<?php
echo "<table>"
. "<tr>"
. "<td colspan=\"" . $numCols . "\">"
. $a . ", " . $b . " and " . $c
. "</td>"
. "</tr>"
. "</table>"
; ?>
Or
<?php
echo "<table>
<tr>
<td colspan='{$numCols}'>
{$a}, {$b}, and {$c}
</td>
</tr>
</table>";
?>
Also don't forget about printf
<?php
printf("<table>"
. "<tr>"
. "<td colspan=\"%d\">%s, %s and %s</td>"
. "</tr>"
. "</table>"
, $numCols
, $a
, $b
, $c
);
?>
The latter is much more readable. It's also more easily editable (you do not have to escape quotes in HTML, for example). And it preserves whitespace without any hassle, which may be preferred, particularly for debugging purposes.
I almost wish PHP would enable print()
and echo()
to automatically convert HTML characters so that people would stop using them to generate HTML.
This should be considered more of a readability and maintenance issue than a performance issue.
Thus, option 2 has a couple concrete advantages:
Let's cite the manual:
The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print().
But please listen to the others and avoid this sort of micro optimization and choose the one that is more legible.
Can I propose a third solution? Have you heard of template engines? They help you create a clear separation between code and presentation which usually leads to cleaner code which is easier to maintain. A popular such template engine is e.g. smarty, but there are hundreds with different strengths.