2009-11-28 33 views
20

比方說文件test.php的是這樣的:在PHP中獲取包含在字符串中的結果?

<?php 
echo 'Hello world.'; 
?> 

我想要做這樣的事情:

$test = include('test.php'); 

echo $test; 

// Hello world. 

任何人都可以點我正確的道路?

編輯:

我最初的目標是拉與HTML混合在一起PHP代碼從數據庫中,並對其進行處理。這是我最終做的:

// Go through all of the code, execute it, and incorporate the results into the content 
while(preg_match('/<\?php(.*?)\?>/ims', $content->content, $phpCodeMatches) != 0) { 
    // Start an output buffer and capture the results of the PHP code 
    ob_start(); 
    eval($phpCodeMatches[1]); 
    $output = ob_get_clean(); 

    // Incorporate the results into the content 
    $content->content = str_replace($phpCodeMatches[0], $output, $content->content); 
} 

回答

49

使用output buffering是最好的選擇。 PS:請記住,如果需要,也可以將輸出緩衝區嵌套到您的內容中。

+6

保存一行:'$ output = ob_get_clean();';-) – 2009-11-29 00:05:03

+0

太棒了,謝謝! – 2009-11-29 12:23:35

4

您也可以讓包含的文件返回輸出,而不是打印它。然後你可以把它變成一個變量,就像你在第二個例子中一樣。

<?php 
    return 'Hello world.'; 
?> 
-4
$test = file_get_contents('test.php'); 
echo $test; //Outputs "Hello world."; 
+1

這將不會解析test.php中的PHP,只是打印它。對字符串執行eval()會比使用帶輸出緩衝的include慢。 – Slashterix 2009-11-29 06:57:50

7

test.php的

<?php 

return 'Hello World'; 

?> 

<?php 

$t = include('test.php'); 

echo $t; 

?> 

只要包含的文件有一個return語句,將工作。

相關問題