简体   繁体   English

CSV文件创建和下载无法在使用PHP的服务器上运行

[英]CSV file create and download not working on server with PHP

I want to create CSV file and download it on server.It is working well on local server but it is printing data on live server and there is no option to download the file. 我想创建CSV文件并将其下载到服务器上。它在本地服务器上运行良好,但是正在实时服务器上打印数据,并且没有下载文件的选项。 here is the code 这是代码

<?php 
    // output headers so that the file is downloaded rather than displayed
    header('Content-Type: application/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    ob_start();
    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');

    // output the column headings
    fputcsv($output, array('Id', 'Emp Name', 'Department','Job Number','REG (hours)','OT1 (hours)','OT2','VAC','SIC','HOL','INPUT'));

    $from_date = $_REQUEST['from_date'];
    $to_date = $_REQUEST['to_date'];
    $class = $_REQUEST['class'];
    $job = $_REQUEST['job'];
    $str = '';
    if ($class!='') {
        $str.= " AND class='".$class."'";
    }
    if ($job!='') {
        $str.= " AND  job_number ='".$job."'";
    }
     $sql = "SELECT * FROM table WHERE punch_in_time BETWEEN '".$from_date."' AND '".$to_date."' $str";
    $res = mysql_query($sql,$Link);

    $weekfrom = array();
    $weekto = array();
    $start_date = date('Y-m-d', strtotime($from_date));
    $end_date = date('Y-m-d', strtotime($to_date));
    $end_date1 = date('Y-m-d', strtotime($to_date . '+ 6 days'));

    for ($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date . ' + 14 days'))) {

      $week = date('W', strtotime($date));
      $year = date('Y', strtotime($date));
      $from = date("Y-m-d", strtotime("{$year}-W{$week}+1 - 1 day")); //Returns the date of monday in week
      if ($from < $start_date)
        $from = $start_date;
      $to = date("Y-m-d", strtotime("{$year}-W{$week}-6 + 1 week"));   //Returns the date of sunday in week
      if ($to > $end_date) {
        $to = $end_date;
      }
      if ($from < $to) {
        array_push($weekfrom, $from);
        array_push($weekto, $to);
      }
    }
    $n = count($weekfrom);
    for ($i = 0; $i < $n; $i++) {
      $week_start[$i] = $weekfrom[$i];
      $week_end[$i] = $weekto[$i] . "\n";
    }

    $num = mysql_num_rows($res);
    $k=1;
    if ($num > 0) {
    // loop over the rows, outputting them
        while ($row = mysql_fetch_array($res)) {
         $classname = 'testClass';
         $empname =    '11233';

          $total_punched_hours = 10;

             $arr = array($k,$empname,$classname,$row['job_number'],$total_punched_hours,'15','1','5','4','55','44');
             $result = fputcsv($output, $arr); 
             $k++;
        }

    }
    fclose($output);

?>

使用页面顶部的ob_start()确实解决了这个问题,希望对其他用户也有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM