2010-09-16 58 views

回答

2

简单:你不能这样做。您可以事先包含该文件,将其存储在一个变量中,然后将其插入到文件中。例如:

$links_contents = file_get_contents('links.php'); 
//$links_contents = eval($links_contents); // if you need to execute PHP inside of the file 
$content = <<<EOF 
{$links_contents} 
EOF; 
+3

这将包含'links.php'的来源,而不是执行的内容。 – Rudu 2010-09-16 19:13:50

+0

运行'file_get_contents'后不要'eval'。它不会像你期望的那样工作。原因是'include'(也就是'links.php'文件)从关闭PHP解释器开始。这就是为什么你需要'<?php'来打开它(它开始于非代码上下文)。 'eval'首先打开解释器(你不需要用'<?php'前缀php代码来让它工作)。所以它不会像你期望的那样工作。更不用说'eval'的其他弊端......所以-1对于那些不好的建议来说不起作用...... – ircmaxell 2010-09-16 20:47:39

0

Heredoc语法仅用于处理文本。您不能包含文件或执行php方法。


资源:

13

你可以这样说:

ob_start(); 
include 'links.php'; 
$include = ob_get_contents(); 
ob_end_clean(); 

$content = <<<EOF 
{$include} 
EOF; 
+3

你可以将ob_get_contents和ob_end_clean结合到ob_get_clean中:) – NikiC 2010-09-16 19:23:54

1

你说的不工作呢?正如在“links.php”的内容不在$内容中?如果多数民众赞成你想要尝试使用输出流重定向(或只是读取文件)。

 
<?php 
ob_start(); 
include 'links.php'; 
$content = ob_get_contents(); 
ob_end_clean(); 

echo "contents=[$content]\n"; 
?> 
+1

*叹息*每当我回答一个没有答案的问题时,在我可以完成打字之前,有3或4个答案。 – troutinator 2010-09-16 19:18:34

1

根本不要使用heredoc。
如果您需要输出您的内容 - 只需按原样输出,而不将其存储在变量中。
输出缓冲的使用可能非常有限,我相信在这里不是这种情况。

只准备您的数据,然后使用纯HTML和PHP输出。
使您的网页这样的(直接从近期其他的答案):

news.php:

<? 
include "config.php"; //connect to database HERE. 
$data = getdbdata("SELECT * FROM news where id = %d",$_GET['id']); 
$page_title = $data['title']; 
$body = nl2br($data['body']); 

$tpl_file = "tpl.news.php"; 
include "template.php"; 
?> 

的template.php:

<html> 
<head> 
<title><?=$page_title?></title> 
</head> 
<body> 
<? include $tpl_file?> 
</body> 

tpl.news.php

<h1><?=$page_title?></h1> 
<?=$body?> 
<? include "links.php" /*include your links anywhere you wish*/?>