การใช้งาน ob_start ใน PHP

ฟังก์ชันนี้จะทำการเก็บค่า output ของตัวสคลิปไว้ใน buffer ถ้าหากมีการเีรียกใช้ฟังก์ชันนี้ script จะไม่มีการแสดง output ออกมา และถ้าเราต้องการนำเอา output ที่ถูกเก็บไว้ใน buffer ออกมาแสดง เราก็สามารถใช้ฟังก์ชัน ob_get_content โดยฟังก์ชันนี้จะให้ค่ากลับมาเป็น string ที่เก็บไว้ใน buffer หรือจะใช้ฟังก์ชัน ob_end_flush ก็จะเป็นการแสดงค่าที่เก็บไว้ใน buffer ออกมาทันที ซึ่งกรณีหลังนี้เป็นกรณีที่เราไม่ต้องการจะทำค่าที่เก็บไว้ไปทำอย่างอื่นต่อครับ โดยที่ฟังก์ชัน ob_start มีรูปแบบการใช้งานดังนี้ครับ

bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )

พูดไปพูดมาเดี๋ยวจะงง ดูตััวอย่างเลยดีกว่า ^^

<?php
function callback($buffer)
{
//replacealltheappleswithoranges
return(str_replace("apples", "oranges", $buffer));
}
ob_start("callback"); ?>
<html>
<body>
<p>It'slikecomparingapplestooranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>

จากโค๊ดข้างบนเราก็จะได้เป็น

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

แหล่งข้อมูล: ob_start manual

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>