2009-11-28 1 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を使うのが最善の策です。


ob_start(); 
include 'test.php'; 
$output = ob_get_clean(); 

PS:必要に応じて出力バッファをハートのコンテンツにネストすることができます。

+6

行を保存する: '$ output = ob_get_clean();' ;-) –

+0

素晴らしい、ありがとう! –

4

インクルードされたファイルに出力する代わりに、出力することもできます。次に、2番目の例のように、変数に変数を取り込むことができます。限り含まれたファイルは、それが動作するreturn文を持っているよう

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

これは、test.phpでPHPを解析せず、そのまま出力します。また、文字列にeval()を実行すると、出力バッファリングでインクルードを使用するよりも遅くなります。 – Slashterix

7

test.phpを

<?php 

return 'Hello World'; 

?> 

<?php 

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

echo $t; 

?> 

関連する問題