php evaluate code before getting file content

2019-05-10 13:37发布

I have a file B590.php which is having a lot of html code and some php code (eg logged in username, details of user).

I tried using $html = file_get_content("B590.php");

But then $html will have the content of B90.php as plain text(with php code).

Is there any method where I can get the content of the file after it has been evaluated? There seems to be many related questions like this one and this one but none seems to have any definite answer.

标签: php file include
5条回答
啃猪蹄的小仙女
2楼-- · 2019-05-10 14:07

To store evaluated result into some variable, try this:

ob_start();
include("B590.php");
$html = ob_get_clean();
查看更多
一纸荒年 Trace。
3楼-- · 2019-05-10 14:14

You can use include() to execute the PHP file and output buffering to capture its output:

ob_start();
include('B590.php');
$content = ob_get_clean();
查看更多
冷血范
4楼-- · 2019-05-10 14:20

If you use include or require the file contents will behave as though the current executing file contained the code of that B590.php file, too. If what you want is the "result" (ie output) of that file, you could do this:

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

Example:

B590.php

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

current.php

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

will output:

do stuff here
<div>Foobar</div>

Whereas, if current.php looks like this:

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

The output will be:

do stuff here
Some more
<div>Foobar</div>

查看更多
一纸荒年 Trace。
5楼-- · 2019-05-10 14:21
    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");

This answer was originally posted on Stackoverflow

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-05-10 14:25
$filename = 'B590.php';
$content = '';

if (php_check_syntax($filename)) {
    ob_start();
    include($filename);
    $content = ob_get_clean();
    ob_end_clean();
}

echo $content;
查看更多
登录 后发表回答