I don't know exactly how output buffering works but as far as know it stores content into some internal variable.

Regarding this, what is the difference of not using output buffering and storing content in my own local variable instead and than echo it at the end of script?

Example with output buffering:

<?php
  ob_start();
  echo "html page goes here";
  ob_end_flush();
?>

And example without using output buffering:

<?php
  $html = "html page goes here";
  echo $html;
?>

What is the difference?

有帮助吗?

解决方案

The main differences:

1.) you can use "normal" output syntax, so for example an echo statement. You don't have to rewrite your problem.

2.) you have better control about the buffering, since buffers can be stacked. You don't have to know about naming conventions and the like, this makes implementations easier where the writing and using side are implemented separate from each other.

3.) no additional logic require to output buffered content, you just flush. Especially interesting if the output stream is something special. Why burden the controlling scope with dealing with that?

4.) you can use the same output implementation regardless of an output buffer has been created. THis is a question of transparency.

5.) you can 'catch' accidentially out bubbled stuff like warnings and the like and simply swallow it afterwards.

[...]

其他提示

Output buffering gives you greater flexibility in separating the concerns of what to output, when to output and how to output without requiring any change to existing code.

You may have existing code that echoes their output instead of returning it; output buffering allows for that code to run without making any changes to it.

Besides the obvious ob_end_flush() you can also use $output = ob_get_contents() followed by ob_end_clean() to capture the output into a variable again. This allows you to write it into a file instead of displaying it on the screen.

Lastly, you can hook filters onto the output buffering system that enable compression on-the-fly.

See also: ob_gz_handler

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top