PHP嵌套輸出緩衝代碼執行個體

來源:互聯網
上載者:User

   這篇文章主要介紹了PHP嵌套輸出緩衝代碼執行個體,本文講解嵌套使用ob系列函數的執行個體,需要的朋友可以參考下

  PHP的輸出緩衝是可以嵌套的。用ob_get_level()就可以輸出嵌套層級。

  測試發現在cli和瀏覽器下輸出結果不一樣(PHP5.4)。

  手冊說明如下:

  ob_get_level() will always return 0 inside a destructor.

  This happens because the garbage collection for output buffers has already done before the destructor is called

  想要正確輸出也很簡單:

   代碼如下:

  ob_end_clean();

  echo ob_get_level(); //0

  回到正題:

   代碼如下:

  ob_end_clean();

  ob_start();

  echo 'php1';//此處並不會在頁面中輸出

  $a = ob_get_level();

  $b = ob_get_contents();//獲得緩衝結果,賦予變數

  ob_clean();

  ob_start();

  echo 'php2';//此處並不會在頁面中輸出

  $c = ob_get_level();

  $d = ob_get_contents();//獲得緩衝結果,賦予變數

  ob_clean();

  ob_start();

  echo 'php3';//此處並不會在頁面中輸出

  $e = ob_get_level();

  $f = ob_get_contents();//獲得緩衝結果,賦予變數

  ob_clean();

  echo 'level:'.$a.',ouput:'.$b.'
';

  echo 'level:'.$c.',ouput:'.$d.'
';

  echo 'level:'.$e.',ouput:'.$f.'
';

  結果如下:

   代碼如下:

  level:1,ouput:php1

  level:2,ouput:php2

  level:3,ouput:php3

  當然,當你關閉某個層級的緩衝,如下測試:

  代碼如下:

  ob_end_clean();

  ob_start();

  echo 'php1';

  $a = ob_get_level();

  $b = ob_get_contents();

  ob_clean();

  ob_start();

  echo 'php2';

  $c = ob_get_level();

  $d = ob_get_contents();

  ob_end_clean(); //清空緩衝並關閉緩衝

  ob_start();

  echo 'php3';

  $e = ob_get_level();

  $f = ob_get_contents();

  ob_clean();

  echo 'level:'.$a.',ouput:'.$b.'
';

  echo 'level:'.$c.',ouput:'.$d.'
';

  echo 'level:'.$e.',ouput:'.$f.'
';

  結果如下:

  代碼如下:

  level:1,ouput:php1

  level:2,ouput:php2

  level:2,ouput:php3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.