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

How to output interpreted PHP-code from file_get_contents() of a PHP file?

我想包含文件 $source 的内容,其中包含 php-code。

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

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

source.php

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

我得到以下信息:

Apples

我要:

2 Apples

有什么方法可以解决这个问题?

而不是使用file_get_contents(), use include()

<?php include($source); ?>

这实际上会 运行 通过 PHP 解释器的代码,而不是仅仅在页面内打印它的 text-contents。

我认为您可能想像其他人提到的那样采用不同的方法来解决您的问题。

我假设您的两个文件在同一目录中,否则您可能需要稍微更改以下内容。

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() returns 内容为字符串,PHP 未解析该字符串,因此您可以无权访问您在 file_get_contents()

调用的文件中声明的任何变量

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

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