In my PHP scripts, I concatenate a lot HTML mixed with some PHP/MySQL data (the first example). Typically, my code looks like a mess because you can’t bring any structure into this mix of code.
So, I was wondering, is the second script slower (or less performance) then the first script?
First script
$message = <div class="label" style="width:200px; float:left; text-align:right;">Organisation:</div>
<div class="input" style="margin-left: 210px;"><b>' . $item1[0]['organisation'] . '</b>
</div><div class="label" style="width:200px; float:left; text-align:right;">Group:</div> <div class="input" style="margin-left: 210px;"><b>' .
$item1[0]['group'] . '</b></div><div class="label" style="width:200px; float:left;
text-align:right;">Name:</div> <div class="input" style="margin-left: 210px;"><b>' . $item1[0]['firstname'] . ' ' . $item[0]['lastname'] . '</b></div>
Second script
$message = <div class="label" style="width:200px; float:left; text-align:right;">Organisation:</div>
$message .= <div class="input" style="margin-left: 210px;"><b>' . $item1[0]['organisation'] . '</b></div>
$message .= <div class="label" style="width:200px; float:left; text-align:right;">Group:</div>
$message .= <div class="input" style="margin-left: 210px;"><b>' .$item1[0]['group'] . '</b></div>
$message .= <div class="label" style="width:200px; float:left; text-align:right;">Name:</div>
$message .= <div class="input" style="margin-left: 210px;"><b>' . $item1[0]['firstname'] . ' ' . $item[0]['lastname'] . '</b></div>
Or are there even better ways to handl PHP generated HTML pages?
Readability should always take priority over performance optimization. The fact that you’re asking which one is faster is an indication that you have not actually traced any performance detriments back to the code in question. What you really seem to be asking is how to make the code more readable, which is understandable since code is meant to be read by humans and executed by computers.
My first advice in these situations is to always exit the PHP parser when you are outputting a large chunk of HTML and only tiny portions of PHP code.
By closing your
PHP tagsto write large chunks of HTML code you simply tell PHP to stop parsing PHP code and output everything that follows as plain text up until anotheropening PHP tagis found.Another option is to use heredoc syntax which doesn’t require all the messy single/double quote escaping.
Variable interpolation is possible directly inside string syntax so the following works: