在 file_get_contents('file.php') 中获取变量

Get variable in file_get_contents('file.php')

我有一个名为 file.php 的文件,内容如下:

<?php

$foo = 'hello';

?>
<div id="fileContent">
   <?php echo($foo) ?>
  ...some content here
</div>

在另一个名为 result.php 的文件中,我使用 file_get_contents():

方法调用 file.php
<div id="resultContent">
  <?php echo(file_get_contents('file.php')) ?>
</div>

但是,我无法在 result.php 文件中打印内部变量 $foo。仅显示为:

<!--?php echo($q); ?-->

我能得到这个结果吗? // 在 result.php 文件中打印 hello

使用 include() 代替 file_get_contents()

file_get_contents() 逐字节读取指定文件但不解释其内容。您正在搜索的是 include() 指令:

<div id="resultContent">
  <?php include('file.php') ?>
</div>