This article mainly introduces PHP nested output buffer code instances. This article describes examples of nested functions using ob series functions. if you need a friend, you can refer to the PHP output cache which can be nested. You can use ob_get_level () to output the nested level.
The test results are different in cli and browser (PHP5.4 ).
The manual description is as follows:
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
It is easy to output the correct output:
The code is as follows:
Ob_end_clean ();
Echo ob_get_level (); // 0
Back to the topic:
The code is as follows:
Ob_end_clean ();
Ob_start ();
Echo 'php1'; // It is not output on the page
$ A = ob_get_level ();
$ B = ob_get_contents (); // Obtain the cache result and assign the variable
Ob_clean ();
Ob_start ();
Echo 'php2'; // This is not output on the page
$ C = ob_get_level ();
$ D = ob_get_contents (); // Obtain the cache result and assign the variable
Ob_clean ();
Ob_start ();
Echo 'php3'; // This is not output on the page
$ E = ob_get_level ();
$ F = ob_get_contents (); // Obtain the cache result and assign the variable
Ob_clean ();
Echo 'level: '. $ a.', ouput: '. $ B .'
';
Echo 'level: '. $ c.', ouput: '. $ d .'
';
Echo 'level: '. $ e.', ouput: '. $ f .'
';
The result is as follows:
The code is as follows:
Level: 1, ouput: php1
Level: 2, ouput: php2
Level: 3, ouput: php3
Of course, when you disable a buffer level, perform the following test:
The code is as follows:
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 (); // clears the cache and closes the cache.
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 .'
';
The result is as follows:
The code is as follows:
Level: 1, ouput: php1
Level: 2, ouput: php2
Level: 2, ouput: php3