【问题标题】:php evaluate code before getting file contentphp 在获取文件内容之前评估代码
【发布时间】:2012-10-13 06:06:16
【问题描述】:

我有一个 B590.php 文件,其中包含大量 html 代码和一些 php 代码(例如登录的用户名、用户详细信息)。

我尝试使用$html = file_get_content("B590.php");

但是$html 将 B90.php 的内容作为纯文本(带有 php 代码)。

有什么方法可以让我在评估后获取文件的内容? 似乎有很多相关的问题,例如this onethis one,但似乎没有一个有明确的答案。

【问题讨论】:

  • 不应该是file_get_contents('B590.php');,最后加上s吗?可能是一个错字,但仍然......

标签: php file include


【解决方案1】:

您可以使用include() 执行 PHP 文件并输出缓冲以捕获其输出:

ob_start();
include('B590.php');
$content = ob_get_clean();

【讨论】:

    【解决方案2】:
        function get_include_contents($filename){
          if(is_file($filename)){
            ob_start();
            include $filename;
            $contents = ob_get_contents();
            ob_end_clean();
            return $contents;
          }
          return false;
        }
    
        $html = get_include_contents("/playbooks/html_pdf/B580.php");
    

    这个答案最初发布在 Stackoverflow 上

    【讨论】:

    【解决方案3】:

    如果您使用includerequire,文件内容将表现得好像当前执行文件也包含该B590.php 文件的代码。如果你想要的是那个文件的"result"(即输出),你可以这样做:

    ob_start();
    include('B590.php');
    $html = ob_get_clean();
    

    例子:

    B590.php

    <div><?php echo 'Foobar'; ?></div>
    

    当前.php

    $stuff = 'do stuff here';
    echo $stuff;
    include('B590.php');
    

    将输出:

    在这里做事

    Foobar

    然而,如果 current.php 看起来像这样:

    $stuff = 'do stuff here';
    echo $stuff;
    ob_start();
    include('B590.php');
    $html = ob_get_clean();
    echo 'Some more';
    echo $html;
    

    输出将是:

    在这里做事
    更多

    Foobar

    【讨论】:

      【解决方案4】:

      要将评估结果存储到某个变量中,请尝试以下操作:

      ob_start();
      include("B590.php");
      $html = ob_get_clean();
      

      【讨论】:

        【解决方案5】:
        $filename = 'B590.php';
        $content = '';
        
        if (php_check_syntax($filename)) {
            ob_start();
            include($filename);
            $content = ob_get_clean();
            ob_end_clean();
        }
        
        echo $content;
        

        【讨论】:

        猜你喜欢
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 1970-01-01
        相关资源
        最近更新 更多