1

使用这个简单的脚本:

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

4 回答 4

6

正确执行此操作, 您应该在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);
?>
于 2013-07-23T15:02:28.547 回答
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);
于 2013-07-23T15:02:32.643 回答
4

ob_get_clean关闭输出缓冲。它真的应该只给你第一个。它显示了两个,因为您有第二层输出缓冲处于活动状态。

尝试使用:

$text[] = ob_get_contents();
ob_clean();
于 2013-07-23T15:03:32.660 回答
4

来自 php.org:

ob_get_clean() 本质上同时执行 ob_get_contents() 和 ob_end_clean()。

ob_get_clean()

当 ob_end_clean() 被调用时,它会关闭缓冲。您需要再次调用 ob_get_start() 以重新打开缓冲。

于 2013-07-23T15:07:17.843 回答