Search code examples
phpechobufferingob-start

How to check if something was echoed in php?


I'm working on a project based on some custom CMS wherein display blocks are returned by CMS's module when I call it. These blocks are drawn using custom functions I've defined across different files. Certainly, ob_start() is used already in CMS itself to preserve the output string. Now, as I see, some of the inner blocks (drawn by the function called by the CMS's module) are drawn only when certain conditions are met (eg, date). So, in some cases, only the outer wrapper of block (div) are drawn as the called function echoes nothing. Now, I want to edit that module by checking if the function echoes something. My problems is that I cannot use something like this:

     $temp = ob_get_contents();
     ob_flush();
     ob_start();
     eval(trim($block->detail));//this is where custom function is called in module
     $block = ob_get_contents();
     ob_flush();
     ob_start();
     echo $temp;
     if($block)
     {
      echo $start.$block.$end;//$start and $end contains div wrapper html
     }

The reason is that this VIEW module is called several times within same components to draw blocks based on different conditions. Doing like what I did above, draws the formerly echoed html (before the view module was called) several times. I'm still stuck at how to avoid that multiple time echoing of the same html. I know this problem is bit complicated but any help would be really appreciated.


Solution

  • I'll write a real answer here. Like I said, you can nest multiple ob_start() together.

    Check the php.net manual: http://php.net/manual/en/function.ob-start.php After the warning message.

    Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

    So your code could be:

    ob_start();
    eval(trim($block->detail));
    $block = ob_get_contents();
    ob_end_clean();
    if($block){
        echo $start.$block.$end;
    }
    

    And that's all, you don't have to stop and start the output buffers again.

    EDIT:

    Or you can even leave the ob_end_clean() ( http://php.net/manual/en/function.ob-get-clean.php )

    Like this:

    ob_start();
    eval(trim($block->detail));
    $block = ob_get_clean();
    if($block){
        echo $start.$block.$end;
    }