2013-07-23 26 views
1

就拿这个简单的脚本:ob_get_clean,只能两次

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

+0

当我尝试它时,我只得到数组中的第一个文本。看起来像ob_get_clean有非常不一致的结果 – StephenTG

+0

@StephenTG我明白你的意思。 PHPFiddle工作两次:http://phpfiddle.org/lite/code/u4z-us5但http://phpcodepad.com/只能工作一次 – Drahcir

回答

4

要做到这一点正确你应该后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); 
?> 
5

ob_start()您需要再次每次调用ob_get_clean()之前调用ob_start()

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); 
4

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

尝试使用:

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

从php.org:

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

ob_get_clean()

当ob_end_clean()被调用时,它关断缓冲。您需要再次调用ob_get_start(),才能恢复缓冲。