1

I have this code

<?php
function testFunc($b){
    ob_start();
    echo "print from callback\n";
    return ob_get_clean();
}

ob_start('testFunc');
echo 'print from buffer';
ob_end_flush();

But I have a following error ob_start(): Cannot use output buffering in output buffering display handlers

I expected the result

print from callback

Please, dont suggest simplify this code, because in my codebase I have nested buffers like this

Evgeny Naumov
  • 347
  • 1
  • 4
  • 15
  • Does this answer your question? https://stackoverflow.com/questions/33936067/cannot-use-output-buffering-in-output-buffering-display-handlers " if you remove the ob_start() from the callback function it's OK" – Monnomcjo Jun 29 '22 at 06:58
  • @Monnomcjo, yes it will work, but how do I print a text via `echo` inside callback? – Evgeny Naumov Jun 29 '22 at 07:05
  • With a callback you can't. But your callback function can return a string, html, etc. – Monnomcjo Jun 29 '22 at 07:50
  • 1
    Does this answer your question? [capturing echo into a variable](https://stackoverflow.com/questions/778336/capturing-echo-into-a-variable) – jspit Jun 29 '22 at 09:43

1 Answers1

0

As said. "You're trying to start a output buffer inside a buffer callback. If you use this code, it will generate that error. But if you remove the ob_start() from the callback function it's OK."

And, if you expected the result to print, return the string or anything else you want to print:

function testFunc($b){
    //ob_start();
    return "print from callback\n";
    //return ob_get_clean();
}

ob_start('testFunc');
echo 'print from buffer';
ob_end_flush();
Monnomcjo
  • 715
  • 1
  • 4
  • 14
  • I can't return a string here. Imagine, I have some "component" which prints html to the screen. I need buffer this component, and return its output as a result callback function – Evgeny Naumov Jun 29 '22 at 07:28
  • Your callback function returns what you want. Including html. However your request is "I expected the result: print from callback". – Monnomcjo Jun 29 '22 at 09:46