Search code examples
phpoutput-buffering

How do I get the ob_start() callback to fire when getting the contents of the buffer?


I've got a script that runs a custom email obfuscation class's Obfuscate() function on the content before displaying it, as follows:

ob_start(array($obfuscator, "Obfuscate"));
include('header.php');
print($html);
include('footer.php');
ob_end_flush();

That all works great. However, I've completely rewritten my view architecture, so I need to run the email obfuscation from within a class function and return that string (which then gets echoed). I initially rewrote the above as:

ob_start(array($this->obfuscator, "Obfuscate"));
include('header.php');
echo($this->content);
include('footer.php');
$wrappedContent = ob_get_contents();
ob_end_clean();

Unfortunately, the $this->obfuscator->Obfuscate() callback is not being fired. I have since learned that ob_get_contents() does not fire the callback, but have tried ob_get_clean() & ob_get_flush() to no avail as well.

So, how can I get the contents of the buffer after the callback has been fired?


Solution

  • Of course, I was overlooking the fact that the only reason to use the callback on ob_start() was because I wanted to run Obfuscate() on the content before it was flushed, but if I'm getting that content back I don't need to run a callback! So, not using a callback and just running ob_get_clean()'s results through Obfuscate() does what I wanted. Doh!

    ob_start();
    include('header.php');
    echo($this->content);
    include('footer.php');
    return $this->obfuscator->Obfuscate(ob_get_clean());