PHP HTML Generation - Using String Concatenation

The question is about various methods for outputting html from PHP; what are the differences in performance between them:

Method 1 - Concatenate Variables

$html = '';
$html .= '<ul>';
for ($k = 1; $k < = 1000; $k++){
    $html .= '<li> This is list item #'.$k.'</li>';
}
$html .= '</ul>';
echo $html;

Method 2 - output buffering

ob_start();
echo '<ul>';
for ($k = 1; $k < = 1000; $k++){
    echo '<li> This is list item #',$k,'</li>';
}
echo '</ul>';

I suspect you are getting some performance hit from constantly modifying and increasing the variable; it is right?

Hooray!

Thanks to GaryF, but I don't need an answer about architecture - this question is about performance. It seems that there are several different opinions / tests that go faster, so there is no answer yet.

+3
source share
8 answers

, Sara Golemon, , . AFAIK , echo, .

+1

, ( ), -, , , , .

Model-View-Control pattern (, Smarty), , .

, .

+4

# 1, HTML- , HTML. HMTL PHP. PHP, .

/, , . , , , - .

, <?php, <?php, - .

, .

, №1 , echo $html; .

+2

, . , - script (- ), - , .

+1

, PHP ( , C #), , , . , , Java # .

sidenote: stringbuilder (untested):

$html = array();
$html[] = '<ul>';
for ($k = 1; $k < = 1000; $k++){
    $html[] = '<li> This is list item #';
    $html[] = $k;
    $html[] = '</li>';
}
$html[] = '</ul>';
echo implode('',$html);
+1

:

  • , , script ( №1 .)

  • php , , . - , , , (40K this)

, . , , , , .

+1

: php: output [] w/join vs $output. =

- .

I have not tested the echo and string construction, but until you use a buffered output echo it should be the fastest due to sequential write to a self-cleaning buffer. (only slowdown occurs in a flash, which you really cannot avoid, even if you perform string concatenation in advance)

+1
source

Something I did not mention is that, as a rule, the PHP guy should work with people who plan to create HTML classes or add styles in another way, so the solution should keep this in mind.

0
source

Source: https://habr.com/ru/post/1697953/


All Articles