【问题标题】:HTML between two separated PHP selectors contains if statement两个分离的 PHP 选择器之间的 HTML 包含 if 语句
【发布时间】:2017-08-09 00:36:03
【问题描述】:
<?php if(1 == 2){echo 1; ?>
   <div>2</div>
<?php echo 3;} ?>

在这段代码中,我希望显示 div,因为它只是 php 之外的一个 html,但事实并非如此。它作为 php 的一部分工作。

这是一个错误还是 PHP 的工作原理?

【问题讨论】:

  • 在 HTML 输出之后才终止 if 块,有什么问题?
  • @Marty 我希望它能够处理 php 中的 html 部分,所以我首先 echo 1,然后显示 html,然后 echo 3,以防声明为真。并且只在声明为假的情况下显示html,但现在它就像在php中回显html。

标签: php html if-statement rendering


【解决方案1】:

重要的是要记住 PHP 是按照它的编写顺序由服务器评估的,大括号告诉 PHP 服务器将 if 作为一个单元评估,然后决定发送什么(例如 HTML 输出)。 可以考虑如下。

<?php 
if (true) {
    //everything in here relies on the above if statement. 
    //I can exit php to write in HTML or plain text,
    //but it remains within the same bracket
}
?>

这允许一些事情。首先,这意味着您可以运行复杂的流程来决定是否应该发送数据。以下面的例子为例。

<?php

// Function ignored as one whole chunk until called
function check_user_login() {
    // check user login and return true for logged in or false if not
}

// If statement checked, now calls the function.
if (check_user_login()) {
    // If you are logged in, then it will evalute everything within these braces. 
    // The result includes printing what is outside the `php` tags.
    ?>
    <div>Secure information that should only be sent if the user is logged in</div>
    <?php
} // now exiting the braces, we will evaluate the rest in order

?>
<h1>My Website</h1>

PHP 将评估该语句,如果它为真(您已登录),那么您将得到大括号中的内容(安全信息),否则就像它从未存在过一样。

这是许多 PHP 框架使用模板系统的原因之一,以便您可以在更直观的结构中工作,而将代码的服务器评估部分放在另一个文件中

【讨论】:

    【解决方案2】:

    您尝试输出的内容都不会出现在屏幕上。

    你在“说”:

    <?php 
    if(1 == 2){
        echo 1; ?>
        <div>2</div>
        <?php echo 3;
    }
    ?>
    

    或者另一种写法是……

    <?php 
    if(1 == 2){
        echo 1;
        ?><div>2</div><?php
        echo 3;
    }
    ?>
    

    这从来都不是真的,所以没有什么可显示的。


    也许这就是你想要达到的目标:

    if(1==2){
        echo 1;
    }
    echo '<div>2</div>';
    if(1==2){
        echo 3;
    }
    // output: <div>2</div>
    

    【讨论】:

    • 我认为通过将php分成两部分,html将被视为只是HTML代码,而不是PHP的一部分。
    • 它在读取脚本时全部呈现(“合并”为 html)。 php 不会因为脚本暂时离开 php (?&gt;) 而被“忽略”。
    • AXAI 它被视为 html 但在 if 语句中,因此它只会在 if 语句为 true 时显示
    【解决方案3】:

    不,这就是 php 的工作方式。括号内的任何内容都将被视为在 if 语句中,即使它在 php 标签之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2016-02-29
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2011-11-25
      相关资源
      最近更新 更多