PHP 預設會即時將輸出(echo、print、HTML 等)發送給客戶端。輸出緩衝機制允許我們攔截這些輸出,暫存於記憶體緩衝區,再由程式決定何時、是否發送。這在模板引擎、壓縮輸出、捕獲錯誤訊息、CLI 進度條等場景極為關鍵。
| 函數 | 用途 | 回傳值 | 常見用法 |
|---|---|---|---|
| ob_start() | 開啟緩衝 | bool | ob_start('callback') 可指定處理函數 |
| ob_get_contents() | 取得緩衝內容 | string|false | 不清空緩衝,僅讀取 |
| ob_get_clean() | 取得並清空緩衝 | string|false | 等同 ob_get_contents() + ob_end_clean() |
| ob_get_flush() | 取得並輸出緩衝 | string|false | 等同 ob_get_contents() + ob_end_flush() |
| ob_end_clean() | 清空並關閉緩衝 | bool | 丟棄內容,不輸出 |
| ob_end_flush() | 輸出並關閉緩衝 | bool | 正常結束輸出 |
| ob_flush() | 刷新緩衝到輸出 | bool | 不關閉緩衝,配合 flush() 即時輸出 |
| ob_implicit_flush() | 設定隱性刷新 | void | 每次輸出自動 flush,CLI 長任務必備 |
在 CLI 模式下,PHP 直接連接標準輸出 (STDOUT),ob_start() 開啟後,內容預設仍會即時顯示於終端機,除非搭配 ob_end_clean() 或 ob_get_clean() 攔截。這與 Web SAPI (FPM/Apache) 行為不同。
<?php
// 錯誤示範:仍會輸出到終端
ob_start();
echo "處理中...\n";
sleep(2);
echo "完成\n";
ob_end_flush(); // 這裡才真正輸出,但前面已經輸出了
// 正確做法:捕獲並靜默處理
ob_start();
echo "處理中...\n";
sleep(2);
$output = ob_get_clean(); // 取得內容並清空緩衝,不輸出到終端
// $output 現在包含 "處理中...\n完成\n"
// 可寫入日誌、資料庫、或條件性輸出
if ($debugMode) {
echo $output;
}
?>
PHP 支援多層 ob_start() 巢狀,每層獨立緩衝。回調函數可在輸出前處理內容(如 gzip 壓縮、關鍵字替換、HTML 最小化)。
<?php
// 多層緩衝範例
ob_start(function($buffer) {
return strtoupper($buffer); // 外層:轉大寫
// ob_end_flush() 時會依序執行回調
});
ob_start(function($buffer) {
return "[內層] $buffer"; // 內層:加前綴
});
echo "hello world";
ob_end_flush(); // 內層先執行 -> "[內層] hello world"
ob_end_flush(); // 外層再執行 -> "[內層] HELLO WORLD"
?>
<?php function render(string $template, array $data = []): string { extract($data); // 將陣列鍵值轉為變數 ob_start(); include $template; // 模板中可直接使用 $title, $content 等變數 return ob_get_clean(); } // 使用 $html = render('views/page.php', [ 'title' => '歡迎頁面', 'user' => ['name' => '張三', 'role' => 'admin'], 'items' => ['蘋果', '香蕉', '橘子'], ]); echo $html; // 或存檔、回傳 API 響應 ?><!-- views/page.php --> <!DOCTYPE html> <html> <head><title><?= htmlspecialchars($title) ?></title></head> <body> <h1>歡迎, <?= htmlspecialchars($user['name']) ?> (<?= $user['role'] ?>)</h1> <ul> <?php foreach ($items as $item): ?> <li><?= htmlspecialchars($item) ?></li> <?php endforeach; ?> </ul> </body></html>進階技巧:即時輸出長時間任務進度
<?php // CLI 長任務即時進度條 ob_implicit_flush(true); // 關鍵:每次輸出自動 flush ob_end_flush(); // 關閉預設緩衝 $total = 100; for ($i = 1; $i <= $total; $i++) { $percent = ($i / $total) * 100; $bar = str_repeat('█', $i / 2) . str_repeat('░', 50 - $i / 2); echo "\r[$bar] $percent% ($i/$total)"; usleep(50000); // 模擬工作 } echo "\n完成!\n"; ?>Web 環境最佳實踐
- 啟用 zlib 壓縮:
php.ini設定zlib.output_compression = On,或程式中ob_start('ob_gzhandler')。- 避免過早輸出:
header()、session_start()、setcookie()必須在任何輸出前呼叫,緩衝可延後輸出時機。- 錯誤捕獲:
ob_start()可捕獲致命錯誤前的輸出,配合register_shutdown_function()實現優雅錯誤頁面。總結
掌握
ob_*函數組合,能精準控制 PHP 輸出行為。關鍵記住:ob_get_clean()是「取得並靜默丟棄」的瑞士刀,ob_implicit_flush()是 CLI 即時輸出的關鍵,巢狀緩衝與回調則是構建模板引擎、中介軟體的基石。