如何在 PHP 中回显 HTML? [英] How can I echo HTML in PHP?

查看:29
本文介绍了如何在 PHP 中回显 HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有条件地输出 HTML 以生成页面,那么在 PHP 4+ 中回显多行 HTML 片段的最简单方法是什么?我需要使用 Smarty 之类的模板框架吗?

I want to conditionally output HTML to generate a page, so what's the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?

echo '<html>', "
"; // I'm sure there's a better way!
echo '<head>', "
";
echo '</head>', "
";
echo '<body>', "
";
echo '</body>', "
";
echo '</html>', "
";

推荐答案

在 PHP 中有几种方法可以回显 HTML.

There are a few ways to echo HTML in PHP.

<?php if(condition){ ?>
     <!-- HTML here -->
<?php } ?>

2.在回声中

if(condition){
     echo "HTML here";
}

对于回显,如果您希望在 HTML 中使用双引号,则必须像这样使用单引号回显:

With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:

echo '<input type="text">';

或者你可以像这样逃避他们:

Or you can escape them like so:

echo "<input type="text">";

3.此处文档

4.Nowdocs(自 PHP 5.3.0 起)

模板引擎用于在主要包含 HTML 的文档中使用 PHP.事实上,PHP 的最初目的是成为一种模板语言.这就是为什么在 PHP 中您可以使用诸如短标签之类的东西来回显变量(例如 <?=$someVariable?>).

3. Heredocs

4. Nowdocs (as of PHP 5.3.0)

Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP's original purpose was to be a templating language. That's why with PHP you can use things like short tags to echo variables (e.g. <?=$someVariable?>).

还有其他模板引擎(例如 Smarty、Twig 等)使语法更加简洁(例如 {{someVariable}}).

There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. {{someVariable}}).

使用模板引擎的主要好处是使设计(表示逻辑)与编码(业务逻辑).从长远来看,它还使代码更清晰,更易于维护.

The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.

如果您还有其他问题,请随时发表评论.

If you have any more questions feel free to leave a comment.

可以在 PHP 文档.

注意: PHP 短标签 <??> 是不鼓励的,因为它们只有在启用 short_open_tag 时才可用 php.ini 配置文件指令,或者 PHP 配置了 --enable-short-tags 选项.从 5.4 开始,无论设置如何,它们都可用.

NOTE: PHP short tags <? and ?> are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option. They are available, regardless of settings from 5.4 onwards.

这篇关于如何在 PHP 中回显 HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆