从 HTML 中分离
凡是在一对开始和结束标记之外的内容都会被 PHP 解析器忽略,这使得 PHP 文件可以具备混合内容。 可以使 PHP 嵌入到 HTML 文档中去,如下例所示。
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
使用条件结构:
示例 #1 使用条件的高级分离术
<?php if ($expression == true): ?>
This will show if the expression is true.
<?php else: ?>
Otherwise this will show.
<?php endif; ?>
要输出大段文本时,跳出 PHP 解析模式通常比将文本通过 echo 或 print 输出更有效率。
注意:
此外注意如果将 PHP 嵌入到 XML 或 XHTML 中则需要使用
<?php ?>
标记以保持符合标准。
+添加备注
用户贡献的备注 3 notes
quickfur at quickfur dot ath dot cx ¶
14 years ago
When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:
<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>
Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:
<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>
Otherwise, it will be:
<html><body>
<p>This is a paragraph.</p>
</body></html>
Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
ravenswd at gmail dot com ¶
15 years ago
One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:
<?php
$file_contents = '<?php die(); ?>' . "\n";
?>
If you try to remove it by turning it into a comment, you get this:
<?php
// $file_contents = '<?php die(); ?>' . "\n";
?>
Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page.
The cure is to either comment it out using /* */ tags, or re-write the line as:
<?php
$file_contents = '<' . '?php die(); ?' . '>' . "\n";
?>
sgurukrupa at gmail dot com ¶
10 years ago
Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements:
<?php for ($i = 0; $i < 5; ++$i): ?>
Hello, there!
<?php endfor; ?>
When the above code snippet is executed we get the following output:
Hello, there!
Hello, there!
Hello, there!
Hello, there!
备份地址:http://www.lvesu.com/blog/php/language.basic-syntax.phpmode.php