将 HTML 转义为 PHP 还是使用 Echo?哪个更好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/505642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escape HTML to PHP or Use Echo? Which is better?
提问by William T Wild
In terms of performance , what would be better. Using PHP to echo all the HTML output so I can pepper it with the various bits of working code and variables or escape HTML to php periodically throughout the documents.
在性能方面,什么会更好。使用 PHP 来回显所有的 HTML 输出,这样我就可以用各种工作代码和变量来填充它,或者在整个文档中定期将 HTML 转义到 php。
I know there may be some readability issues but I'm not to worried about that.
我知道可能存在一些可读性问题,但我并不担心。
Thanks all!
谢谢大家!
Example 1
示例 1
echo '<html>',
'<body>',
'The content of the ',$container,' element is displayed in your ', $other_container,
'</body>',
'</html>';
OR
或者
<html>
<body>
The content of the <?php echo $container; ?> element is displayed in your <?php echo $other_container; ?>
</body>
</html>
采纳答案by nickf
It's all about which you find the most readable. Of course, this will vary with each situation. If you were doing an entire page, and there were large sections which did not have any PHP in it, then I'd break out of PHP and just write the plain HTML, whereas if there was a section which had a lot of PHP variables, I'd do it all in PHP.
这就是您认为最具可读性的所有内容。当然,这会因情况而异。如果你正在做一个完整的页面,并且有很大的部分没有任何 PHP,那么我会跳出 PHP 并只编写纯 HTML,而如果有一个部分有很多 PHP 变量,编号做这一切在PHP 中。
For example:
例如:
<table>
<tr>
<td colspan="<?php echo $numCols; ?>">
<?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
</td>
</tr>
</table>
versus:
相对:
<?php
echo "<table>"
. "<tr>"
. "<td colspan=\"" . $numCols . "\">"
. $a . ", " . $b . " and " . $c
. "</td>"
. "</tr>"
. "</table>"
; ?>
Or
或者
<?php
echo "<table>
<tr>
<td colspan='{$numCols}'>
{$a}, {$b}, and {$c}
</td>
</tr>
</table>";
?>
Also don't forget about printf
也不要忘记 printf
<?php
printf("<table>"
. "<tr>"
. "<td colspan=\"%d\">%s, %s and %s</td>"
. "</tr>"
. "</table>"
, $numCols
, $a
, $b
, $c
);
?>
回答by Stephane Grenier
Whichever is easiest to read.
哪个最容易阅读。
The performance difference is pretty negligible compared to almost any other issue you'll encounter. Definitely readability is hands down the first issue here.
与您遇到的几乎任何其他问题相比,性能差异几乎可以忽略不计。绝对可读性是这里的第一个问题。
回答by Georg Sch?lly
Let's cite the manual:
让我们引用手册:
The example given here is contrived, of course, but for outputting large blocksof text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print().
当然,这里给出的示例是人为设计的,但对于输出大块文本,退出 PHP 解析模式通常比通过 echo() 或 print() 发送所有文本更有效。
But please listen to the others and avoid this sort of micro optimization and choose the one that is more legible.
但请听取其他人的意见,避免这种微优化,选择更清晰的优化。
Can I propose a third solution? Have you heard of template engines? They help you create a clear separation between code and presentation which usually leads to cleaner code which is easier to maintain. A popular such template engine is e.g. smarty, but there are hundreds with different strengths.
我可以提出第三个解决方案吗?你听说过模板引擎吗?它们帮助您在代码和表示之间创建清晰的分离,这通常会导致代码更清晰,更易于维护。一个流行的这样的模板引擎是例如smarty,但有数百种不同的优势。
回答by Paolo Bergantino
It's pretty irrelevant to the overall speed of your app which one you go with.
这与您使用哪个应用程序的整体速度无关。
That being said, I know you said you don't care, but please use the 2nd one as it's about a million times easier to read. And readability is huge.
话虽如此,我知道你说你不在乎,但请使用第二个,因为它比阅读容易一百万倍。可读性是巨大的。
回答by notruthless
I don't know about the performance of this, but within PHP you can also use what I believe is called a "Heredoc", which I think helps with readability within this sort of output.
我不知道它的性能,但在 PHP 中你也可以使用我认为被称为“Heredoc”的东西,我认为这有助于提高这类输出的可读性。
Nickf's example:
尼克夫的例子:
<table>
<tr>
<td colspan="<?php echo $numCols; ?>">
<?php echo $a; ?>, <?php echo $b; ?>, and <?php echo $c?>
</td>
</tr>
</table>
becomes:
变成:
<?php
echo <<<EOT
<table>
<tr>
<td colspan="$numCols">
$a , $b, and $c
</td>
</tr>
</table>
EOT;
?>
I do believe that ultimately readability is a subjective thing, so your mileage may vary!
我相信最终的可读性是一个主观的东西,所以你的里程可能会有所不同!
Ruth
露丝
回答by ólafur Waage
It falls into the realm of micro optimizations. The largest part of your time falls into initializing the PHP engine starting the work.
它属于微优化领域。您大部分时间都花在初始化 PHP 引擎开始工作上。
So unless you have an order of tens of thousands of lines (or even more), you shouldn't be concerned with it.
所以除非你有数万行(甚至更多)的订单,否则你不应该关心它。
To add, i did a small test of a million lines where i used php to print them and where i used php to call a c program that did the same thing and the difference was minuscule.
另外,我做了一个一百万行的小测试,我使用 php 打印它们,并使用 php 调用执行相同操作的 ac 程序,差异很小。
A little more info.
多一点信息。
What is happening in the 2nd example is that you are "turning on/off" PHP, its not exactly what is happening but for this example it fits.
在第二个示例中发生的事情是您正在“打开/关闭”PHP,这并不完全是正在发生的事情,但对于这个示例来说它适合。
The thing you should be more worried about, is that code going to have a lot of logic around it? Am i going to split that string into even more strings or even place it in different places? Is this the View of a MVC application?
您应该更担心的是,该代码是否会有很多逻辑?我是要把那个字符串分成更多的字符串,还是把它放在不同的地方?这是 MVC 应用程序的视图吗?
For 1 and 2 it could be a toss up between either method. But for 3 i would go with method 2 for these reasons.
对于 1 和 2,这可能是两种方法之间的折腾。但是对于 3,出于这些原因,我会使用方法 2。
A view in a MVC web application is mostly html/css. So i want to see that be formatted correctly and i want to see in my editor the html coloring. So that is a plus.
MVC Web 应用程序中的视图主要是 html/css。所以我想看到它的格式正确,我想在我的编辑器中看到 html 着色。所以这是一个加分项。
回答by bobince
In terms of performance... it's not important. Readability of the code is king, a tiny fraction of a percent of performance difference isn't going to change anything.
在性能方面......这并不重要。代码的可读性是王道,性能差异的一小部分不会改变任何东西。
The raw HTML version is usually the easiest to read (and probably has the best performance too for what it's worth - but what it's worth is: nothing). This is no surprise: PHP is an HTML templating language, the whole pointis interleaving HTML at a language syntax level.
原始 HTML 版本通常是最容易阅读的(并且可能也有最好的性能,因为它的价值 - 但它的价值是:什么都没有)。这并不奇怪:PHP 是一种 HTML 模板语言,重点是在语言语法级别交错 HTML。
Look at nickf's code to see how to keep it readable. Indenting is important! Put a level of indenting inside each PHP control structure too, so you can keep track of them. eg.:
查看 nickf 的代码以了解如何保持其可读性。缩进很重要!在每个 PHP 控制结构中也放置一个缩进级别,以便您可以跟踪它们。例如。:
<?php if ($error) { ?>
<p> Oh no, error! </p>
<?php } ?>
Finally, when outputting content, such as $container in your example, you must always htmlspecialchars() it, or you'll have an application full of HTML-injection security holes, like every other PHP newbie (and even many professional developers, sadly). This matters whichever method you use to output content.
最后,在输出内容时,例如您的示例中的 $container,您必须始终使用 htmlspecialchars(),否则您将拥有一个充满 HTML 注入安全漏洞的应用程序,就像其他 PHP 新手一样(甚至许多专业开发人员,遗憾的是)。无论您使用哪种方法输出内容,这都很重要。
Because htmlspecialchars is quite an annoyingly long function name, you could try defining your own shortcut function:
因为 htmlspecialchars 是一个相当长的函数名,你可以尝试定义自己的快捷函数:
<?php
function h($s) {
echo(htmlspecialchars($s, ENT_QUOTES));
}
?>
<ul>
<?php foreach ($things as $thing) { ?>
<li> <?php h($thing['name']) ?> </li>
<?php } ?>
</ul>
回答by Mario
Code as if the next programmer taking over the project is a serial killer. In other words, use the second option you mentionned.
就像下一个接管项目的程序员是连环杀手一样编写代码。换句话说,使用您提到的第二个选项。
回答by Cory House
This should be considered more of a readability and maintenance issue than a performance issue.
这应该更多地被视为可读性和维护问题,而不是性能问题。
Thus, option 2 has a couple concrete advantages:
因此,选项 2 有几个具体的优点:
- Code coloring. With option 1 everything is colored as an echo statement which makes reading HTML more difficult.
- Intellisense - With many IDE's, HTML within a PHP echo statement won't engage intellisense, so you'll be typing all that HTML by hand.
- 代码着色。使用选项 1,所有内容都被着色为 echo 语句,这使得阅读 HTML 更加困难。
- 智能感知 - 对于许多 IDE,PHP echo 语句中的 HTML 不会参与智能感知,因此您将手动输入所有 HTML。
回答by CONvid19
I prefer to use php heredocfunction, this way I don't need to escape any characters, ex:
我更喜欢使用 php heredoc函数,这样我就不需要转义任何字符,例如:
<?php
$title = "heredoc is cool!!!";
$mySite = "http://www.php.net";
echo <<<LOL
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> $title </title>
<link rel="shortcut icon" href="$mySite/favicon.ico">
<link rel="search" type="application/opensearchdescription+xml" href="$mySite/phpnetimprovedsearch.src" title="Add PHP.net search">
<link rel="alternate" type="application/atom+xml" href="$mySite/releases/feed.php" title="PHP Release feed">
<link rel="alternate" type="application/atom+xml" href="$mySite/feed.atom" title="PHP: Hypertext Preprocessor">
<link rel="canonical" href="$mySite/manual/en/language.types.string.php">
<link rel="shorturl" href="$mySite/types.string">
<link rel="contents" href="$mySite/manual/en/index.php">
<link rel="index" href="$mySite/manual/en/language.types.php">
<link rel="prev" href="$mySite/manual/en/language.types.float.php">
<link rel="next" href="$mySite/manual/en/language.types.array.php">
LOL;
?>
Note:
笔记:
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
Heredoc 文本的行为就像一个双引号字符串,没有双引号。这意味着heredoc中的引号不需要转义,但仍然可以使用上面列出的转义码。变量被扩展,但在 heredoc 中表达复杂变量时必须像使用字符串一样小心。

