2011-08-01 37 views
1

我想將一個文件的內容加載到一個字符串中。這個文件包含一些php代碼,需要一些變量才能正常工作。將多個文件內容加載(使用變量)到字符串中的最佳方式是什麼?

什麼是最有效的方法來實現這一目標?

以下是我認爲將是很好的做到這一點的方法:

與會話變量:

for ($i = 0; $i < 10; $i++) 
{ 
    $_SESSION[$key] = $i; 
    $content .= file_get_contents($fileName); 
} 

然後,我可以從加載文件訪問變量。

使用GET方法:

for ($i = 0; $i < 10; $i++) 
{ 
    $content .= file_get_contents($fileName."?key=$i"); 
} 

使用post方法:

for ($i = 0; $i < 10; $i++) 
{ 
    $postData = http_build_query($i); 
    $opts = array('http' => 
        array(
         'method' => 'POST', 
         'header' => 'Content-type: application/x-www-form-urlencoded', 
         'content' => $postData 
       ) 
    ); 

    $context = stream_context_create($opts); 
    $content .= file_get_contents($fileName, false, $context); 
} 

我向所有人開放的更佳方式來做到這一點。

這裏有一個文件內容的爲例:

<?php echo $_GET['key']; /*(or $_POST or $_SESSION)*/ ?> 

將輸出

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
+0

請解釋你想要完成什麼,輸入/輸出 – Dani

+0

什麼是10倍循環? – Phil

+0

@這是一個隨機數,我只是想表明我想多次加載文件。 –

回答

2

聽起來像是你要使用的輸出緩衝,例如

$content = ''; 
for ($i = 0; $i < 10; $i++) { 
    ob_start(); 
    include $fileName; 
    $content .= ob_get_contents(); 
    ob_end_clean(); 
} 

這是假設你的文件看起來像

echo $i, PHP_EOL; 
+0

但你的$ foo變量是如何傳遞給file.php的? –

+0

@JeanPhilippe我更新了我的答案,以更好地匹配您問題的代碼。當你包含一個文件時,它繼承了調用範圍 – Phil

+0

輸出緩衝('ob_')是實現這個目標的最好方法,很好的答案 –

相關問題