2010-09-16 88 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*/?>