2009-10-07 117 views
2

我有以下情況。使用PHP無法渲染輸出到屏幕?

我有一個PHP網站女巫包含約3個動態內容的網頁。我想將這個靜態內容渲染到另一個文件。例如。 contact.php - > contact.html

我的代碼看起來像這樣

ob_start(); 
$content = require_once 'contact.php'; 
ob_end_flush(); 
file_put_contents("contact.html", $content); 

不知怎的,這是不工作; - ?(

+1

爲什麼不讓瀏覽器試圖加載'contact.php'? – pavium 2009-10-07 12:18:02

回答

9

require_once()不返回由腳本輸出的內容你需要得到存儲在輸出緩衝區中的腳本輸出:

ob_start(); 
require_once('contact.php'); 
$content = ob_get_clean(); 

file_put_contents('contact.html', $content); 

ob_get_clean()

獲取當前緩衝區內容,並且 刪除當前輸出緩衝區。

ob_get_clean()實質上執行 ob_get_contents()和 ob_end_clean()。

http://php.net/ob_get_clean

2
ob_start(); 
require_once('contact.php'); 
$content = ob_get_contents(); 
ob_end_clean(); 
file_put_contents("contact.html", $content); 
2

require_once打開文件,並嘗試分析它作爲PHP。它不會返回它的輸出。什麼,你可能找的是:

<?php 
ob_start(); 
require_once('file.php'); 
$content = ob_get_contents(); 
ob_end_flush(); 
// etc... 
?> 

這樣一來,既腳本保存在$內容的數據,並將它們轉儲到標準輸出。如果您只希望填充$ content,請使用ob_end_clean()而不是ob_end_flush()

2

結帳ob_get_flush(http://www.php.net/manual/en/function.ob-get-flush.php

基本上嘗試做

if(!is_file("contact.html")){ 
    ob_start(); 
    require_once 'contact.php'; 
    $content = ob_get_flush(); 
    file_put_contents("contact.html", $content); 
}else{ 
    echo file_gut_contents("contact.html"); 
} 

這應該從contact.php緩衝輸出並在需要時傾倒。