簡體   English   中英

CSV文件創建和下載無法在使用PHP的服務器上運行

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

我想創建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);

?>

使用頁面頂部的ob_start()確實解決了這個問題,希望對其他用戶也有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM