14

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;
4
  • there is a fifth option, looks more like 4 but does not use output buffer. Commented Jun 6, 2016 at 12:21
  • 2
    I think a good read might be this from SO: stackoverflow.com/questions/4148031/… Pekka give a good answer there Commented Jun 6, 2016 at 12:24
  • 1
    I usually use option 5: HEREDOC Commented Jun 6, 2016 at 14:56
  • HEREDOC is ok but I don't use that because closing tag can not be indented. Commented Jun 6, 2016 at 16:14

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.