Search code examples
phpoutput-buffering

Pausing output buffer in php


Here's my problem. I want to be able to buffer only the contents of the tables but not the header. Is it possible to pause the output buffering in php so that I could skip the buffering on the table headers and resume again at the beginning of the actual content?

<?php ob_start(); ?>
<table>
<tr>
    <th>Account</th>
    <th>Quarter</th>
    <th>Amount</th>
</tr>
    <?php 
    foreach($tc_item as $v){ 


    if($v->dbl_amt != 0){
    ?>
    <tr>
    <!-- Nature of Collection -->
        <td id="nature"><?php echo $v->strDescription; ?></td>
     <!-- Account Code -->     
        <td id="account"><?php echo $v->str_details; ?></td>
     <!-- Amount -->
        <td id="amount"><?php echo number_format($v->dbl_amt,2, '.', ''); ?></td>

    </tr>
    <?php } ?>
    <?php } ?>

</table>
<?php 
$_SESSION['or_details'] = ob_get_contents();
?>

Solution

  • If you don't want to buffer the whole table, then don't buffer it:

    <table>
      <thead></thead>
      <?php ob_start();?>
      <tbody></tbody>
      <?php $tbody = ob_get_flush(); ?>
    </table>
    

    If you want to buffer the whole table, but want the table body separately, then add another level of buffering:

    <?php ob_start();?>
    <table>
      <thead></thead>
      <?php ob_start();?>
      <tbody></tbody>
      <?php $tbody = ob_get_flush(); ?>
    </table>
    <?php $table = ob_get_clean(); ?>
    

    Alternatively, you can flush the current buffer without creating a new one. I don't recommend this because it makes your code harder to follow. It's also silly since if you're just going to flush without capturing the string, you might as well not buffer in the first place:

    <?php ob_start()?>
    <table>
      <thead></thead>
      <?php ob_flush();?>
      <tbody></tbody>
      <?php $tbody = ob_get_contents(); // only contains output since last flush ?>
    </table>
    <?php ob_end_flush(); ?>