0

What is the faster way to output html in PHP that contains PHP variables?

Version A:

<div id="example"><?php echo $var; ?></div>
... much more like this

or

Version B:

$html = array();

$html[] = '<div id ="example">';
$html[] = &$var;
$html[] = '</div>';
$html[] = '... much more like this';

echo implode( '', $html );

2 Answers 2

1

PHP - Hypertext Pre Processor

In fact, PHP is a templating engine itself. In any case variant A is better, but such code isn't the best solution for bigger projects. Try looking on MVC design pattern, which will help you separate database/business logic from the representation part of your application. Using an template engine (like Twig, Smarty, Blitz etc.) will help you achieve this too.

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

Comments

0

In this case it is faster to mix html and php. Version B, will essentially hold a big array in memory, and in the end loop through all the elements. So it will be slower, than just print/echo the data right away. Either way, I won't recommend either approach. I will suggest using a template engine and provide it with data, instead of mixing php and html, this way you can keep markup and logic completely separate. This is often done as a part of a MVC pattern as @Wrong described.

7 Comments

So is Version A the common way to do this? It looks very unclean.
Yes, version A is the common way to do this. Anyway, look for my answer above
@user2429266 If you think this looks unclean, you should take a look at Template engines (i.e. smarty.net) which makes you able to seperate php logic and html more neatly.
@Joren smarty.net is quite big, and has a lot of features which some would say doens't belong in an template engine, I can recommend twig as template engine, it is small easy extensible, and very fast. If you prefer no kind of logic what so ever in a template language, you could look at moustache for php.
I have a strictly separated logic&template codebase. This concerns just the template files. And they look terrible with the mixed way. Thanks.
|

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.