doushang2571 2012-05-10 08:02
浏览 37
已采纳

渲染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!

  • 写回答

3条回答 默认 最新

  • doushou9028 2012-05-10 08:09
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?