【问题标题】:Running an included PHP file运行包含的 PHP 文件
【发布时间】:2012-03-02 05:33:49
【问题描述】:

我有一个包含另一个脚本的 php 脚本(我将调用主脚本)。伪代码是这样的

include '.../somescript.php'

if(some conditions are met){
          show the contents of somescript.php
}

我只希望这个脚本显示在屏幕上(而不是重定向到那个页面)。它主要是 HTML,但我不确定显示内容的最佳方式。我可以将它包装在一个函数 showScript() 中,它会回显所有 HTML,并在我的主脚本中调用此函数:

include '.../somescript.php'

if(some conditions are met){
          showScript();
}

但我想知道是否可以直接运行脚本作为主脚本的补充?很抱歉,如果最后一句话听起来有点乱码,我不知道如何正确表达我的意思。

【问题讨论】:

  • 你希望这个包含和 if 语句等显示在 SO 中吗?作为 html 的输出?
  • 该脚本包含几个功能,主要是数据库查询和会话检查,然后显示大量 HTML。我希望这个脚本作为主脚本的一部分运行,因为我不希望用户被重定向到另一个页面。

标签: php html include


【解决方案1】:

如果“somescript.php”文件都是HTML,你可以这样做:

<?php
  if (some condition) {
      include('../somescript.php');
  }
?>

如果“somescript.php”的内容都是纯 HTML,那么它会显示在屏幕上。如果该文件中有 PHP,它将在满足“某些条件”并包含该文件时执行(此后所有函数声明等都可以访问)。

如果您问了其他问题,但我误解了您的问题,请告诉我...

【讨论】:

    【解决方案2】:

    如果我没听错你可以使用缓冲。

    ob_start();
    include '.../somescript.php'
    
    if(some conditions are met){
      echo ob_get_contents();
    }
    ob_end_clean();
    

    【讨论】:

      【解决方案3】:

      创建两个单独的脚本,一个包含所有 sql 查询和一个可以显示在 HTML 上的输出数组。另一个文件作为仅 HTML 文件,然后在 mainscript.php 顶部和 if 语句下包含 query.php 包含包含 html 的 showhtmlscript.php,

      query.php 的数组变量输出,比如 $output,可以在 showhtmlscript.php 中使用

      <table>
      <tr><td>$output['name']</td><td>$output['age']</td></tr>
      </table>
      

      你需要这个

      include(query.php);
      
      if(something is set){
      include(somehtmlscript.php);
      }
      

      【讨论】:

        【解决方案4】:
        <?php
          if (some conditions are met) {
              include('../somescript.php');
          }
        ?>
        

        或选择输出缓冲

        <?php
        ob_start();
        include '.../somescript.php'
        
        if(some conditions are met){
          echo ob_get_contents();
        }
        ob_end_clean();
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-26
          • 2011-08-02
          • 2012-02-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-13
          相关资源
          最近更新 更多