为什么要将额外的信息添加到使用PHP头下载的Excel文件中


Why the extra information getting added to the Excel file which is to be downloaded using PHP headers?

我正在使用一些库将PHP数组数据写入excel文件。当我将数据写入excel文件并返回一些成功消息时,它工作得很好。除了预期的数组外,没有其他数据被添加到文件中。

但是当我使用标题来下载相同的文件功能时,页面上存在的一些额外信息(如标题菜单,一些标题,页面底部的版权行等)被添加到文件中。如何避免将这些额外的信息添加到excel文件?下面是我的代码:

<?php
  require_once( CORE_PATH."/libs/excelwriter.inc.php" );
  $objRebateReports   = new RebateReports();
  if($_POST['btnDownload']!='') {
    $rebate_ret = $objRebateReports->GetRebateReport($_POST);
    $rebate_data = $objRebateReports->GetResponse();
    $t=time();
    $fileName = ADMIN_ROOT."modules/rebates/rebate_report_".$t.".xls";
    $excel = new ExcelWriter($fileName);      
    if($excel==false) {
      echo $excel->error;
      die;  
    }       
    $myArr = array('Sr. No.', 'Product','Manufacturer','User Name','Date','Status','Transaction Date');
    $excel->writeLine($myArr, array('text-align'=>'center', 'color'=> 'red'));
    $id=1;
    foreach ($rebate_data as $value) {
      $temp_rebate_data =array();
      $temp_rebate_data['id'] = $id;
      $temp_rebate_data['product'] = "";
      $temp_rebate_data['manufacturer'] = "";            
      $temp_rebate_data['user_name'] = $value['customer_first_name']."".$value['customer_last_name'];
      $temp_rebate_data['date'] = $value['created_at'];
      $temp_rebate_data['status'] = $value['request_status'];
      $temp_rebate_data['transaction_date'] = "";
      $row = $temp_rebate_data;
      $excel->writeLine($row, array());
      $id++;
  }
  $excel->close();
  //Following is the header information in order to download the excel file
  header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
  header("Content-Disposition: attachment; filename=".$fileName);
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Cache-Control: private",false);
  //Below is the success message after printing the data successfully to the file
  //echo "Data written to file $fileName Successfully.";                 
 }
?>

您应该为此使用输出缓冲。

        //start of the page
        ob_start(); 

        //ur code
       //headers
       ob_clean();
       flush();
       readfile($file);
        exit;

我想这会解决你的问题