Output Buffering yêu cầu PHP giữ dữ liệu đầu ra trong bộ nhớ đệm thay vì gửi từng mảnh đến trình duyệt. Dữ liệu được lưu trong biến và gửi một lần tại cuối script.
Ví dụ
<?php
ob_start();
echo "Hello";
$ob1 = ob_get_contents();
echo "Tutorials Point";
$ob2 = ob_get_contents();
ob_end_clean();
var_dump($ob1, $ob2);
?>
Kết quả
string(5) "Hello"
string(20) "HelloTutorials Point"
Giải thích
ob_get_contents() lấy toàn bộ dữ liệu trong buffer kể từ ob_start().
Lợi ích
- Giảm thời gian tải và render HTML (gửi một lần).
- Khắc phục lỗi
"Cannot modify header information - headers already sent"khi set cookie/header sau khi đã có output.