【问题标题】:ob_get_clean, only works twiceob_get_clean,只能工作两次
【发布时间】:2013-07-23 14:59:15
【问题描述】:

使用这个简单的脚本:

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

【问题讨论】:

  • 当我尝试它时,我只得到数组中的第一个文本。似乎 ob_get_clean 的结果非常不一致
  • @StephenTG 我明白你的意思。 PHPFiddle 工作两次:phpfiddle.org/lite/code/u4z-us5phpcodepad.com 只工作一次

标签: php output-buffering ob-start


【解决方案1】:

要做到这一点正确你应该在ob_get_clean()之后做ob_start()

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

【讨论】:

    【解决方案2】:

    每次拨打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);
    

    【讨论】:

      【解决方案3】:

      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() 以重新打开缓冲。

        【讨论】:

          猜你喜欢
          • 2021-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-28
          • 1970-01-01
          • 1970-01-01
          • 2011-02-17
          • 2015-09-01
          相关资源
          最近更新 更多