javascript - 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>
解决方案
要直接回答您的问题,标题必须位于文件的首位。将所有标题设置移到第一位,然后再进行其他所有设置(可能除了 config.php,具体取决于您在其中所做的工作)
确切的错误是由您在第 5 行中的输出引起的。只要您输出任何内容,就会(自动)发送标头。发送输出后,发送更多标头为时已晚。
还要注意您收到的其他评论,您的代码很容易受到攻击,并且有更好的方法来做到这一点。
推荐阅读
- data-structures - 如何使用计步法求矩阵链乘法的时间复杂度?
- python - 如何加载 CIFAR10.pickle
- python - 匹配字典键和值,并使用 Python 更新值
- node.js - Azure 函数(blob 触发器)使用 Nodejs 读取 CSV 文件
- javascript - 无法在 Graphql vue.js 中发布
- localization - Zeta 资源编辑器 - 如何更新现有语言资源文件
- amazon-athena - 检查行是否包含列或默认值,如果不包含
- pandas - 地理数据框:如何基于地理数据框显示几何图形
- android - 使用Android上的ON SCREEN后退按钮时如何取消订阅消息中心?
- react-native - 如何使用 burp 套件拦截反应原生应用程序?