渲染HTML和PHP的最有效方法[关闭]

What is the most efficient way to render a page with PHP and HTML?

Concatenating

$html = '<span><img src="page.png" alt="page" />'.$variable1.'</span>';
echo $html

Replacing variables

$html = "<span><img src=\"page.png\" alt=\"page\" />{$variable1}</span>";
echo $html;

Inline PHP tags - This doesn't seem practical even if it is the most efficient on a large scale

<span><img src="page.png" alt="page" /><?php echo $variable1; ?></span>

Please assume you are generate a whole page. I used the snippets above as an example of each method.

Thanks!

It really depends on the goal you try to achieve.

If it's just rendering a simple page, the most efficient way is to concatenate code using single quote (based on benchmark) (even if the difference is not so important).

But I'm guessing you are building a website, and you will use html+php widely. If so, I recommend you to use a template engine, or, directly PHP.

Using any template engine will reduce the performance, of course, but it will improve the readability of your project and structure it in a better way. The ratio "lost performance"/"readability - maintain" is worth it. You should go for it (again, if you plan to render many html pages). See MVC Design Pattern.

Now, for the template engine, I would recommend you to use PHP directly since it has first been developed for this purpose. You can find many template engines that just finally use php in the templates, and the same apply for Frameworks. If you take a look at Code Igniter for example, you'll see that the templates are made of php.

Now, for security reasons, using PHP in your template greatly depends on who is going to edit templates. If it's only you, or someone you have a total trust, you should go for it. If your users will be able to edit the templates (for any kind of reasons), then I absolutely should avoid it, because they can do whatever they want on your server, including hitting the database, viewing all the files (even configurations ones) etc.

The best way is: readable and maintainable.

That being said I'd probably use a template engine (like twig or smarty), but if not available I definitly go for inline php tags (as used in views in Zend Framework views and Symfony success templates).

If I had to generate html inside php, I'd go for sprinft('<img src="%s">", $src'); or concatination.

I really, really dislike the use of {$var} or $html = "$var".

There's not enough performance difference to matter or measure. Do the most readable thing. In my (many) PHP apps I mostly use embedded PHP substitutions with short tags:

<p><?= $text ?></p>