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

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

问题描述

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

  echo'< html>',\\\
; //我确定有更好的方法!
echo'< head>',\\\
;
echo'< / head>',\\\
;
echo'< body>',\\\
;
echo'< / body>',\\\
;
echo'< / html>',\\\
;


解决方案

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

1。在PHP标签之间



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



2。回声



  if(condition){
echoHTML here;
}

使用回声,如果您希望在HTML中使用双引号,您必须使用单引号回声如此:

  echo'< input type =text>'; 

或者您可以像这样转义它们:

  echo< input type = \text \>; 



3。 Heredocs



4。 Nowdocs(自PHP 5.3.0开始)



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

还有其他模板引擎(如Smarty,Twig等)使语法更加简洁(例如 {{someVariable}}使用模板引擎的主要好处是使设计(演示逻辑)与编码(业务逻辑)分离。它还使得代码更加清晰,并且从长远来看更易于维护。



如果您有任何问题,请随时发表评论。
有关 PHP文档

上帝保佑!




注意:不鼓励PHP短标签<??>> ,因为它们仅在if启用 short_open_tag php.ini配置文件指令,或者PHP配置了 - enable-short-tags 选项。 无论5.4以上的设置如何,都可以使用它们

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>', "\n"; // I'm sure there's a better way!
echo '<head>', "\n";
echo '</head>', "\n";
echo '<body>', "\n";
echo '</body>', "\n";
echo '</html>', "\n";

解决方案

There are a few ways to echo HTML in PHP.

1. In between PHP tags

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

2. In an echo

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

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. 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?>).

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. Further reading is available on these things in the PHP Documentation.

God Bless!


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天全站免登陆