t tran
t tran

Reputation: 1605

PHP Force download includes HTML source code

I have a form which runs a query against a mySQL database upon hitting the submit button. I want to capture that result result and force the user to download a file. I got everything working but the file being downloaded includes the source code of my HTML page. Note that the code below is within my main index file so it has other code above it such as the doctype, header, body tags.

    <?php
    # Convert result to csv and push use to download if user pressed "Download" button
    if(isset($_POST["downloadquery"])) {
        $fp = fopen('php://output', 'w');
        ob_start();
        if ($fp && $result) {
            fputcsv($fp, $headers); # populate header
            while ($row = $result->fetch_array(MYSQLI_NUM)) {
                fputcsv($fp, array_values($row)); #populate rows
            }
        }
        $content = ob_get_clean();
        $filename ='queryResults' . date('Ymd');

        // Output CSV-specific headers
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: private', false);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '.txt";');

        exit($content);
    }
    ?>

Upvotes: 2

Views: 1986

Answers (1)

Renato Leite
Renato Leite

Reputation: 791

If you don't need of the html code (body, headers, ...) in TXT file, you need separate this code in another file.

Html code:

<html>
  <body>
    <form action="downloadPage.php"></form>
  </body>
</html>

PHP (downloadPage.php):

<?
       $fp = fopen('php://output', 'w');
        ob_start();
        if ($fp && $result) {
            fputcsv($fp, $headers); # populate header
            while ($row = $result->fetch_array(MYSQLI_NUM)) {
                fputcsv($fp, array_values($row)); #populate rows
            }
        }
        $content = ob_get_clean();
        $filename ='queryResults' . date('Ymd');

        // Output CSV-specific headers
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: private', false);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '.txt";');

        exit($content);

?>

Upvotes: 1

Related Questions