首页 > 解决方案 > PHP不生成Excel文件

问题描述

我正在使用以下脚本在我的 php 中生成一个 excel 文件。它给了我以下错误。这可能是什么原因-

警告:无法修改标头信息 - 标头已由 C:\xampp\htdocs\geochronology\library\admin\ 中的(输出开始于 C:\xampp\htdocs\geochronology\library\admin\generate-excel.php:45)发送在第 56 行生成-excel.php

<?php
// Database Connection file
include('includes/config.php');
?>
<table border="1">
<thead>
<tr>
<th>Sr.</th>
<th>User Name</th>
<th>Affiliation</th>
<th>Sample Type</th>
<th>Sample ID</th>
<th>Date</th>
</tr>
</thead>
<?php
// File name
$filename="Sample-summary";
// Fetching data from data base
        $search=$_POST['search2'];
        $option=$_POST['option2'];
        $period=$_POST['period2'];
        $datefrom=$_POST['datefrom2'];
        $dateto=$_POST['dateto2'];
        $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));


            if($period ==null){
            $sql = "SELECT tbluser.user,tbluser.affiliation,tblfacility.type,tblfacility.sampleid,tblfacility.time,DATE_FORMAT(tblfacility.time, '%d-%m-%y') AS formatted_date 
            FROM tblfacility 
            JOIN tbluser on tbluser.id=tblfacility.user 
            where ".$search." ='".$option."' ";}
            else{
            $sql="SELECT * FROM tblfacility JOIN tbluser on tbluser.id=tblfacility.user where ".$search." ='".$option."' AND time between '".$datefrom."' and '".$dateto."' ";
            }
            $query = $dbh->prepare($sql);
            $query->execute();
            $results=$query->fetchAll(PDO::FETCH_OBJ);
            //echo "<prep>";
            //echo "this is the final";
            print_r($sql);
            $cnt=1;         
            foreach($results as $result){
?>
            <tr>
                <td><?php echo $cnt;?></td>
                <td><?php echo $row['user'];?></td>
                <td><?php echo $row['affiliation'];?></td>
                <td><?php echo $row['type'];?></td>
                <td><?php echo $row['sampleid'];?></td>
                <td><?php echo $row['time'];?></td>
            </tr>
<?php
$cnt++;
// Genrating Execel  filess
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$filename."-Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
            }
            ?>
</table>

标签: javascriptphphtmlmysql

解决方案


要直接回答您的问题,标题必须位于文件的首位。将所有标题设置移到第一位,然后再进行其他所有设置(可能除了 config.php,具体取决于您在其中所做的工作)

确切的错误是由您在第 5 行中的输出引起的。只要您输出任何内容,就会(自动)发送标头。发送输出后,发送更多标头为时已晚。

还要注意您收到的其他评论,您的代码很容易受到攻击,并且有更好的方法来做到这一点。


推荐阅读