使用PHP在CSV服务器上创建和下载CSV文件

时间:2013-12-17 09:55:33

标签: php csv

我想创建CSV文件并将其下载到服务器上。它在本地服务器上运行良好,但它在实时服务器上打印数据,没有下载文件的选项。 这是代码

<?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);

?>

1 个答案:

答案 0 :(得分:0)

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

相关问题