What is best way to return HTML code from PHP function? In matter of speed and usability?
I am using variant 1, because it is most understandable but people says me that is slowest because I have code inside " " that must be parsed.
I think that this is not duplicate question from What is the best practice to use when using PHP and HTML? because I talking about returning code from function, not just echo HTML from included file.
CASE 1
return "
<div class='title'>
<h5>
<a href='$permalink'>$title</a>
</h5>
</div>
<div id='content'>
$content
</div>
";
CASE 2
$output = '
<div class="title">
<h5>
<a href="' . $permalink . '">' . $title . '</a>
</h5>
</div>
<div id="content">' .
$content .'
</div>
';
return $output;
CASE 3
$output = '<div class="title">';
$output .= '<h5>';
$output .= '<a href="' . $permalink . '">' . $title . '</a>';
$output .= '</h5>';
$output .= '</div>';
$output .= '<div id="content">';
$output .= $content;
$output .= '</div>';
return $output;
CASE 4
ob_start();
?>
<div class='title'>
<h5>
<a href="<?= $permalink ?>"><?= $title ?></a>
</h5>
</div>
<div id='content'>
<?= $content ?>
</div>";
<?php
return ob_get_clean();
CASE 5
$output = <<<HTML
<div class='title'>
<h5>
<a href='$permalink'>$title</a>
</h5>
</div>
<div id='content'>
$content
</div>
HTML;
return $output;
case 6:
Let PHP handle the data and let your templating tool handle the HTML (you can use PHP as the template tool, but something like Twig is much better)
<?php
function doSomething(){
return [
'permalink' => 'https://some.where',
'title' => "Title",
'Content' => "Hello World!",
];
}
$template = $twig->loadTemplate('template.twig.html');
$template->render(doSomething());
//content of template.twig.html
<div class='title'>
<h5>
<a href='{{permalink}}'>{{title}}</a>
</h5>
</div>
<div id='content'>
{{content}}
</div>
Twig documentation
http://twig.sensiolabs.org/documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With