2016-04-13 62 views
0

我有一个外部的php文件是这样的:内容导入一个PHP变量

<!DOCTYPE> 
<head>... 
... 
<body> 

<p><?php echo $content;?></p> 
.. 

,在我的代码:

$content = 'sample text'; 
$body = include("layout/mailtemplate.php"); 

你可以看到它有PHP和HTML代码(并将文件外部的$content传递给包含文件)

有什么方法可以将此文件的内容存储到php变量中吗? ($身体的这里内容是 “1”!)

而且我测试

$body = file_get_contents('layout/mailtemplate.php'); 

它的工作原理,但我不能错过$content到文件。

(我知道我可以通过GET传递它),但我有很多变量。有一种更简单的方法吗?

+2

为什么要重新发明轮子? PHP有许多模板引擎。 'file_get_contents'作为一个字符串获得文件的内容,不评估代码,然后你需要解析它以用你的内容替换它的必要部分。 'include'将评估内容,但不返回字符串。 – Eihwaz

回答

0

是的,你可以。您需要使用输出缓冲:

ob_start(); 
$content = 'sample text'; 
include("inc.php"); 
$body = ob_get_contents(); 
ob_end_clean(); 

var_dump($body); // string(11) "sample text"