开发者

PHP: Exporting HTML table to Excel includes entire form?

I have a php file which shows an html form, and on submit, creates an html table from mysql data, and exports it to excel.

My issue is that the entire html form is outputted to the excel file along with the table data.

My code is:

<html form..>

<?php
if(isset($_POST['submit'])){
//get sql data and create html table in variable (ie $data="<table>..")

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo "$data";}
?>

i want only "$data" to show in my .xls, but instead the 开发者_高级运维whole <form> is displaying, submit buttons and all.

thank you.


No output should be sent to the browser before the header call.

Define your html form below the submit process.

<?php
if(isset($_POST['submit'])){
//get sql data and create html table in variable (ie $data="<table>..")

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo "$data";
}
?>

<html form..>


All the data written to the output buffer will be included. Header calls should preferably be done before any output. But in the case of how your file is organised you could do:

<html form..>

    <?php if(isset($_POST['submit'])){ 
     //get sql data and create html table in variable (ie $data="<table>..")
     // Clean the output buffer so it won't mess up your excel export 
     ob_clean();

    header("Content-type: application/vnd.ms-excel"); 
    header("Content-Disposition: attachment; filename=$file"); 
    echo $data; // no need for quotes here since you only echo your variable
    }
    ?>


If you do your logic in the presentation layer (conditional ifs in your html file) than maybe it would suffice to wrap your form code into

if(!isset($_POST['submit'])){

Thou the best way would be to redirect the export action to some other script :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜