Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for return HTML from PHP function

Tags:

php

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;
like image 510
SaleCar Avatar asked Jun 06 '16 12:06

SaleCar


1 Answers

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

like image 122
exussum Avatar answered Oct 22 '22 07:10

exussum