2011-03-14 22 views
4

我試圖讓我的代碼清理一些文件(有點像庫)。但其中一些文件將需要運行PHP。將文件包含到一個變量中

所以我想要做的是一樣的東西:

$include = include("file/path/include.php"); 
$array[] = array(key => $include); 

include("template.php"); 

比的template.php我會:

foreach($array as $a){ 
    echo $a['key']; 
} 

所以我要存儲什麼發生在PHP中運行後,變量稍後傳遞。

使用file_get_contents不會運行PHP它將其存儲爲一個字符串,所以有沒有這樣的選擇或我運氣不好?

UPDATE:

所以像:

function CreateOutput($filename) { 
    if(is_file($filename)){ 
     file_get_contents($filename); 
    } 
    return $output; 
} 

還是你的意思爲每個文件創建一個功能?

回答

10

看來你需要使用Output Buffering Control - 見尤其是ob_start()ob_get_clean()功能。

使用輸出緩衝將允許您將標準輸出重定向到內存,而不是將其發送到瀏覽器。


這裏有一個簡單的例子:

// Activate output buffering => all that's echoed after goes to memory 
ob_start(); 

// do some echoing -- that will go to the buffer 
echo "hello %MARKER% !!!"; 

// get what was echoed to memory, and disables output buffering 
$str = ob_get_clean(); 

// $str now contains what whas previously echoed 
// you can work on $str 

$new_str = str_replace('%MARKER%', 'World', $str); 

// echo to the standard output (browser) 
echo $new_str; 

,你會得到的輸出是:

hello World !!! 
+0

因此,如果我做了一個包含而不是回聲,然後對變量做ob_get_clean它應該工作? – jefffan24 2011-03-14 20:59:02

+0

如果你包含文件迴應的東西,它會得到緩衝 - 你將能夠得到它的變量*(希望我理解的問題)* – 2011-03-14 21:02:20

+0

是的,你做了,謝謝。 – jefffan24 2011-03-14 21:06:47

0

file/path/include.php是怎麼樣的?

您必須通過http調用file_get_contents以獲取其輸出,例如,

$str = file_get_contents('http://server.tld/file/path/include.php'); 

倒不如通過一個函數來修改你的文件,以輸出一些文字:

<?php 

function CreateOutput() { 
    // ... 
    return $output; 
} 

?> 

不是包括它之後,調用函數來獲取輸出。

include("file/path/include.php"); 
$array[] = array(key => CreateOutput()); 
+0

上面我的評論(需要使用代碼標記)檢查更新。 – jefffan24 2011-03-14 20:54:29

+0

@ jefffan24,不,那不是我的意思,那樣會和以前完全一樣。我的意思是直接在函數中執行文件_ $ filename_中的動作並將其保存在變量$ output中,然後將其發回。可以一直使用變量或使用[輸出緩衝](http://php.net/manual/en/book.outcontrol.php)。很難說我們什麼時候不知道你的文件及其中的內容 - 你在那裏用PHP執行什麼操作。 – Czechnology 2011-03-14 21:00:12

相關問題