通过GET将CSV文件下载到同一页面

My code:

<form action="" method="GET">
    <p><input name="date_start" type="text" id="datestart" /> to
        <input name="date_end" type="text" id="dateend" /></p>
    <button type="submit">Generate!</button>
</form>
<?php
if ($_GET["date_start"] && $_GET["date_end"]) {   
    $users_list = mysql_query("my query", $dbc) or die(mysql_error());

    $output = fopen("php://output", 'w') or die("Can't open php://output");
    header("Content-Type:application/csv");
    header("Content-Disposition:attachment;filename=user_list.csv");

    fputcsv($output, array("First Name", "Last Name", "Email", "Mobile", "Site"));
    while ($row = mysql_fetch_assoc($users_list)) {
        fputcsv($output, $row);
    }
    fclose($output) or die("Can't close php://output");
}
?>

Basically I'm sending my FORM to the same page, below the form I check for my GET variables and try to force a CSV file download, but instead of downloading, the content of my query is simply being printed.

I think this is because my headers have already been sent, but is there a way to download the file at all?

Put your php code above the html form.

I came across this while making my own form/CSV using POST.

Figured I would add some more info with my own example.

excerpt from my example:

if($_POST[submit] === "Export" && _other_test_here_ )
{
    //export CSV of all entries
    include('csv-export.php');
}
else
{
    HTML GOES HERE
    <form method="post" name="form-export" action="" onsubmit="">
        <input type="submit" name="submit" value="Export" />
        <input type="hidden" name="uid" value="<?php echo($row['uid']); ?>" />
        <textarea name="comment" readonly="true" ><?php echo($row['comment']); ?></textarea>
    </form>
}

The included php file handles accessing the DB and outputting the CSV. Use this in your own way. I found it was nice to be able to include it from another file without any trouble.

Putting the IF and php at the top actually causes my Export button to not even refresh the page, the visitor simply gets a standard popup asking if they wish to open or save the CSV file. Very convenient.