如何从PHP文件的file_get_contents()输出解释的PHP代码?

时间:2016-01-19 09:43:15

标签: php file-get-contents

我想要包含文件$source的内容,其中包含php代码。

// using_source.php
$source = '../filepath/..';

<?php echo file_get_contents($source); ?>

source.php

<?php $multiplicator = 2; ?>
<?php echo 1 * $multiplicator; ?> Apples <br>

我得到以下信息:

  

苹果

我想:

  

2个苹果

解决这个问题的方法有哪些?

2 个答案:

答案 0 :(得分:2)

使用file_get_contents()

,而不是使用include()
<?php include($source); ?>

这实际上将通过PHP解释器运行代码,而不是仅仅在页面内打印其文本内容。

答案 1 :(得分:1)

我认为你可能想像其他人提到的那样对你的问题采取不同的方法。

我打算假设你的两个文件在同一个目录中,如果没有,你可能需要稍微修改一下。

<强> source.php

<?php

// The variable we want to work with
$multiplicator = 2;

<强>的index.php

<?php 

require 'source.php';

echo (1 * $multiplicator) . ' Apples';

我不确定你的用例是什么,说实话,这似乎有点奇怪,但上述至少应该解决你的问题。

您当前代码无法正常工作的原因是file_get_contents()将内容作为字符串返回,该字符串未被PHP解析,因此您无法访问在a中声明的任何变量您通过file_get_contents()

调用的文件

希望有帮助,这里是file_get_contents()require的DOC: http://php.net/manual/en/function.file-get-contents.php

http://php.net/manual/en/function.require.php