CSV文件在浏览器中显示内容,而不是从浏览器下载

时间:2014-05-27 11:18:28

标签: php sql csv download

我想从我的数据库中的某些结果创建一个csv文件。但它显示内容而不是提示下载。

我知道有很多关于此的问题,但对我来说没有运气。

 if(isset($_POST['export'])){

     $resultExport = mysql_query("SELECT question.id, question.question, answer, A, B, C, D, question.publish
                                  FROM question
                                  INNER JOIN packagequestion
                                  ON question.id = packagequestion.questionid
                                  WHERE packagequestion.packageid = '".$packageID."' AND question.publish = 1
                                  ORDER BY question.id DESC"); 

    if (!$resultExport) die('Couldn\'t fetch records');

            $num_fields = mysql_num_fields($resultExport); 
            $headers = array();

            for ($i = 0; $i < $num_fields; $i++) 
            {     
                $headers[] = mysql_field_name($resultExport , $i); 
            }

                $fp = fopen('php://output', 'w');

            if ($fp && $resultExport) 
            {
                // name the file by current category and package
                $filename = $categorie."".$packageName;     
                header('Content-Type: text/csv');
                header('Content-Disposition: attachment; filename='.$filename.".csv");
                header('Pragma: no-cache');    
                header('Expires: 0');
                fputcsv($fp, $headers);

                while ($row = mysql_fetch_row($resultExport)) 
                {
                    fputcsv($fp, array_values($row)); 
                }
            die; 
        }    





}

2 个答案:

答案 0 :(得分:0)

   hope this will help you


   <?php

   include 'connection.php'; 
   // Fetch Record from Database

   $output = "";
   $sql = mysql_query("select* from tablename");//your query
   $columns_total = mysql_num_fields($sql);
   // Get The Field Name

   for ($i = 0; $i < $columns_total; $i++) {
   $heading = mysql_field_name($sql, $i);
   $output .= '"'.$heading.'",';
   }
   $output .="\n";

   // Get Records from the table

  while ($row = mysql_fetch_array($sql)) {
  for ($i = 0; $i < $columns_total; $i++) {
  $output .='"'.$row["$i"].'",';
  }
  $output .="\n";
  }

  // Download the file

  $filename = "myFile.csv";
  header('Content-type: application/csv');
  header('Content-Disposition: attachment; filename='.$filename);

  echo $output;
  exit;

  ?>

答案 1 :(得分:0)

为此您只需从代码中删除以下行。

标题('Content-Type:text / csv');