Search code examples
phpoutput-bufferingob-get-contents

Php ob_get_contents fail


I am using ob_get_contents() to create a html file from php file. On development machine sometimes it works but on the test machine it did not work.

<html>
<body>
    <div>
       //some html content
    </div>
</body>
</html>

<?php
    ob_start();
    file_put_contents('./pdfreportresult.html', ob_get_contents());

    require_once (APP_DIR . 'assessment/wkhtmltopdf/snappy-master/src/autoload.php');

    use Knp\Snappy\Pdf;

    $snappy = new Pdf(APP_DIR . 'assessment/wkhtmltopdf/wkhtmltopdf.exe');

    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="report.pdf"');
    echo $snappy->getOutput(APP_DIR . 'assessment/pdfreportresult.html');
    ob_end_clean();
?>

I checked test machine's php.ini for output_buffering and it is "On" like on development machine. When i checked my created html file "pdfreportresult.html" it is empty or half-content is exist.

Maybe issue can related with buffer size and i tried ob_clean() instead of ob_end_clean() still not working.


Solution

  • Start the buffer before you start outputting content. Also, clean the buffer once you're done with it.

    <?php
    ob_start();
    ?>
    <html>
    <body>
        <div>
           //some html content
        </div>
    </body>
    </html>
    
    <?php
    file_put_contents('./pdfreportresult.html', ob_get_contents());
    ob_end_clean();
    ...