ob_get_clean,只能工作两次

时间:2013-07-23 14:59:16

标签: php output-buffering ob-start

采用这个简单的脚本:

ob_start();
$text = array();

echo 'first text';
$text[] = ob_get_clean();

echo 'second text';
$text[] = ob_get_clean();

echo 'third text';
$text[] = ob_get_clean();

echo 'fourth text';
$text[] = ob_get_clean();

print_r($text);

输出:

third textfourth textArray
(
    [0] => first text
    [1] => second text
    [2] => 
    [3] => 
)

但我希望:

Array
(
    [0] => first text
    [1] => second text
    [2] => third text
    [3] => fourth text
)

PHPFiddle

4 个答案:

答案 0 :(得分:5)

要正确执行 ,您应该在ob_start()之后ob_get_clean()进行<?php ob_start(); $text = array(); echo 'first text'; $text[] = ob_get_clean(); ob_start(); echo 'second text'; $text[] = ob_get_clean(); ob_start(); echo 'third text'; $text[] = ob_get_clean(); ob_start(); echo 'fourth text'; $text[] = ob_get_clean(); print_r($text); ?>

{{1}}

答案 1 :(得分:5)

每次致电ob_start()之前,您需要再次致电ob_get_clean()

ob_start();
$text = array();

echo 'first text';
$text[] = ob_get_clean();

ob_start();
echo 'second text';
$text[] = ob_get_clean();

ob_start();
echo 'third text';
$text[] = ob_get_clean();

ob_start();
echo 'fourth text';
$text[] = ob_get_clean();

print_r($text);

答案 2 :(得分:4)

ob_get_clean关闭输出缓冲。它应该只给你第一个。它显示了两个,因为你有第二层输出缓冲激活。

尝试使用:

$text[] = ob_get_contents();
ob_clean();

答案 3 :(得分:4)

来自php.org:

  

ob_get_clean()基本上执行ob_get_contents()和ob_end_clean()。

ob_get_clean()

当调用ob_end_clean()时,它会关闭缓冲。你需要再次调用ob_get_start(),重新开启缓冲。