15

我已经查看了有关 ob_start() ob_end_clean() ob_end_flush() 的 php 手册。而且我已经看到了关于该主题的不同示例,无论如何我修改了示例,但此时我很困惑。这是脚本。

ob_start();
echo "Hello x, ";

ob_start();
echo "Hello y, ";

ob_start();
echo "Hello z, ";

ob_start();
echo "Hello World";
$ob_2 = ob_get_contents();
ob_end_clean();

echo "Galaxy";
$ob_1 = ob_get_contents();
ob_end_clean();

echo " this is OB_1 : ".$ob_1;
echo "<br>  and this is OB_2  : ".$ob_2;

这个脚本的输出是:

你好 x,你好 y,这是 OB_1:你好 z,银河

这是 OB_2:Hello World

------------------------------------------

为什么输出不是这样?

这是 OB_1:你好 x,你好 y,你好 z,银河

这是 OB_2:Hello World

我错过了什么?

4

2 回答 2

42

我将注释您的代码以解释发生了什么。所有输出缓冲区都初始化为空,这是标准的:

ob_start(); // open output buffer 1
echo "Hello x, "; // echo appended to output buffer 1

ob_start(); // open output buffer 2
echo "Hello y, "; // echo appended output buffer 2

ob_start(); // open output buffer 3
echo "Hello z, "; // echo appended to output buffer 3

ob_start(); // open output buffer 4
echo "Hello World"; // echo appended output buffer 4
$ob_2 = ob_get_contents(); // get contents of output buffer 4
ob_end_clean(); // close and throw away contents of output buffer 4

echo "Galaxy"; // echo appended to output buffer 3
$ob_1 = ob_get_contents(); // get contents of output buffer 3
ob_end_clean(); // close and throw away contents of output buffer 3

// at this point, $ob_2 = "Hello World" and $ob_1 = "Hello z, Galaxy"
// output buffer 1 = "Hello x," and output buffer 2 = "Hello y,"

echo " this is OB_1 : ".$ob_1; // echo appended to output buffer 2

// output buffer 2 now looks like "Hello y,  this is OB_1 : Hello z, Galaxy" 

echo "<br>  and this is OB_2  : ".$ob_2; // echo appended to output buffer 2

// output buffer 2 now looks like:
//   "Hello y,  this is OB_1 : Hello z, Galaxy<br> and this is OB_2  : Hello World"

// output buffer 2 implicitly flushed by end of script
// output from buffer 2 captured by (appended to) output buffer 1
// output buffer 1 now looks like:
//   "Hello x, Hello y,  this is OB_1 : Hello z, Galaxy<br> and this is OB_2  : Hello World"
// output buffer 1 implicitly closed by end of script. This is when your output
// actually gets printed for this particular script.
于 2012-05-04T01:22:49.320 回答
23

输出缓冲区像堆栈一样工作。创建一个缓冲区并在其中回显“Hello x”,然后创建另一个缓冲区并在其中回显“Hello y”,然后创建第三个缓冲区并在其中回显“Hello z”。“Hello World”进入第四个缓冲区,该缓冲区由对 的调用关闭ob_end_clean(),因此您回到第三个缓冲区。当您ob_get_contents()在回显“Galaxy”后调用时,您将获得第三个缓冲区的内容。

如果您ob_get_contents()在此代码末尾再次调用,您将获得第二个缓冲区中的“Hello y”。如果你ob_end_close()再这样ob_get_contents(),你会从第一个缓冲区中得到“Hello x”。

于 2012-05-04T01:18:20.883 回答