2012-01-05 95 views
15

是否有可能做出类似这样的事情?包含PHP文件作为字符串

// file.php 
$string = require('otherfile.php'); 
echo $string; 

// otherfile.php 
<!DOCTYPE html> 
<html> 
<head><title>Test</title></head> 
<body> 
<?php require 'body.php';?> 
</body> 
</html> 

// body.php 
<p>Lorem ipsum something</p> 

并得到这个输出?

<!DOCTYPE html> 
<html> 
<head><title>Test</title></head> 
<body> 
<p>Lorem ipsum something</p> 
</body> 
</html> 

我知道代码不起作用,但我希望你明白我的意思。

+1

参见:http://stackoverflow.com/questions/1683771/execute-a-php-file-and-return-the-result-as-a-string – BeRecursive 2012-01-05 23:06:45

+0

这看起来有点像你正在重新发明模板。也许你可以使用模板引擎? – 2012-01-05 23:11:21

+0

我认为模板引擎重新发明PHP,但它是一个意见的问题:) – Yaniro 2012-01-05 23:14:05

回答

39

file.php

ob_start(); 
include 'otherfile.php'; 
$string = ob_get_clean(); 
+1

PHP网站http://www.php.net/manual/en/function.ob-start.php上有一个parse()函数,用于添加错误报告并允许您将变量传递给模板文件。 – Bink 2012-11-19 15:33:00

+1

这个解决方案比Mark Ba​​kers更好 - 如果你想在otherfile.php里执行PHP代码 – Gmeister4 2018-01-18 09:48:37

+1

在我的wordpress插件里,这对我来说非常合适,我可以在短代码中调用包含文件。谢谢@SmokeyPHP – 2018-02-05 12:40:05

-2
<?php require "otherfile.php"; 
+0

我想你不明白我说的 – SnackerSWE 2012-01-06 03:21:56

+0

-1'd它肯定确实会出现你误解了这个问题; @SnackerSWE希望包含一个文件,将其解析为php,然后将其作为字符串获取,但不会将其包含到当前页面中。 – 2014-09-25 06:46:25

3

另一个很酷的事情就知道了,但SmokeyPHP的回答可能会更好:

<?php 
$var = require 'myfile.php'; 

myfile.php:

<?php 
return 'mystring'; 
9
$string = file_get_contents('otherfile.php',TRUE); 
echo $string 

使用的file_get_contents true参数的()意味着它会使用搜索包含路径,就像正常的包含或要求

+1

如果这个文件中有PHP,它不会被解释,你需要使用eval或类似的东西。 – Manhim 2012-01-06 01:29:24

+1

Manhim,我知道它需要回避(如果被回显用于展示)......这是我阅读OP想要的东西。 – 2012-01-06 07:30:11

1

我猜你已经解决了这个问题。我在这些日子里所面临的同样的问题,我发现了一个漂亮的解决方案使用eval,和的file_get_contents输出缓冲功能:

ob_start(); 
eval('?>' . file_get_contents($fileToRequire, TRUE) . '<?php '); 
$this->output = ob_get_contents(); 
ob_end_clean(); 

必须关心的只有一件事,就是把标签<?php ?>之间的PHP代码,不离开任何PHP标签打开。

“?>”是强制性的,否则你将eval函数得到错误

希望它能帮助!

干杯!