【问题标题】:How do I use PHP to display one html page or another?如何使用 PHP 显示一个或另一个 html 页面?
【发布时间】:2010-01-24 09:59:56
【问题描述】:

我想用 PHP 和 if 语句,我想做

if ($variable){
display html page1
}
else {
display html page2
}

我该怎么做?请注意,我不想将用户重定向到其他页面。

--编辑-- 我对其中一个文件执行此操作没有问题,但对另一个文件执行此操作太麻烦了。

--编辑-- 这是到目前为止的编码:

<?PHP
include 'uc.php';
if ($UCdisplay) {
    include("under_construction.php");
}
else {
    include("index.html");
}
?>

我的问题是,如果我必须为每个 php 页面创建一个 html 页面,那将是非常复杂和令人困惑的,所以我需要一些方法来显示完整的 html 页面,而不是使用 include("index.html" )

【问题讨论】:

    标签: php html if-statement


    【解决方案1】:
    if ($variable){
      include("file1.html");
    }
    else {
      include("file2.html");
    }
    

    【讨论】:

      【解决方案2】:

      最简单的方法是将您的 HTML 放在两个单独的文件中并使用 include():

      if ($variable) {
          include('page1.html');
      }
      else {
          include('page2.html');
      }
      

      【讨论】:

        【解决方案3】:

        使用三元运算符:

         include(($variable ? 'page1' : 'page2').'.html');
        

        【讨论】:

          【解决方案4】:

          如果您想避免“为每个 php 页面创建一个 html 页面”,那么您可以这样做,将“真实”内容直接放在 PHP 页面中。

          <?PHP
          include 'uc.php';
          if ($UCdisplay) {
              include("under_construction.php");
              exit;
          }
          ?>
          <html>
          
          <!-- Your real content goes here -->
          
          </html>
          

          这个想法是这样的:如果$UCdisplay 为真,则显示您正在建设的页面,并在exit; 处停止执行 - 不会显示其他任何内容。否则,程序流程“失败”并输出页面的其余部分。每页内容都有一个 PHP 文件。

          您可以通过将检查$UCdisplay 的代码直接移动到uc.php 中来回避这个问题;这将防止您必须在每个文件的顶部编写相同的 if 语句。诀窍是在包含构建页面后使用代码exit

          【讨论】:

            【解决方案5】:

            对于那些仍在寻找的人: 请参阅 php 中的 readfile(); 函数。它在一个功能中读取和打印文件。

            定义

            int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
            

            读取文件并将其写入输出缓冲区。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-04-22
              • 2020-07-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-04-02
              相关资源
              最近更新 更多