2012-01-05 93 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函數得到錯誤

希望它能幫助!

乾杯!