2014-11-03 57 views
-1

我有一个函数可以从sql查询创建一个cvs文件。从php生成器格式化csv文件

function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) { 

     if($attachment) { 
      // send response headers to the browser 
      header('Content-Type: text/csv'); 
      header('Content-Disposition: attachment;filename='.$filename); 
      $fp = fopen('php://output', 'w'); 
     } else { 
      $fp = fopen($filename, 'w'); 
     } 

     $result = mysql_query($query, $db_conn) or die(mysql_error($db_conn)); 

     if($headers) { 
      // output header row (if at least one row exists) 
      $row = mysql_fetch_assoc($result); 
      if($row) { 
       fputcsv($fp, array_keys($row)); 
       // reset pointer back to beginning 
       mysql_data_seek($result, 0); 
      } 
     } 

     while($row = mysql_fetch_assoc($result)) { 
      fputcsv($fp, $row); 
     } 

     fclose($fp); 
    } 

的事情是,生成的文件看起来像这样

A1          | B1 
2014-10-30,333333333333333333333334 

我怎么能拆分的日期是在A1和B2中的数字?这将是很好,如果我也可以命名我的标题(A1到Date ..)

+0

万岁Excel中,你不能只是打开一个CSV文件(再)你必须导入它。只有这样它才能正确显示。 – 2014-11-03 12:53:55

+0

您需要知道您的基本csv阅读器(如Microsoft Excel或Open Office Excel,...)会注意到您的csv的第一个“行”作为标题。所以你基本上只需要把你的文件写成这样:'$ csv =“A1; B1; \ r2014-10-30; 3333333334; \ r2011-11-12; 576666;”;'etc ... – 2014-11-03 13:17:10

+0

请[不要使用'mysql_ *'函数](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php),它们不再被维护,并[正式弃用](https://wiki.php.net/rfc/mysql_deprecation)。学习[准备的语句](http://en.wikipedia.org/wiki/Prepared_statement),并使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。 [本文](http://php.net/manual/en/mysqlinfo.api.choosing.php)将帮助你决定。 – 2014-11-03 13:41:45

回答

0

默认情况下fputcsv使用逗号作为分隔符,而Excel需要一个分号分隔符。 您可以通过添加分号分隔符的第三个参数fputcsv函数来得到“正确”的修改功能出类拔萃的CSV文件:

function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) { 

     if($attachment) { 
      // send response headers to the browser 
      header('Content-Type: text/csv'); 
      header('Content-Disposition: attachment;filename='.$filename); 
      $fp = fopen('php://output', 'w'); 
     } else { 
      $fp = fopen($filename, 'w'); 
     } 

     $result = mysql_query($query, $db_conn) or die(mysql_error($db_conn)); 

     if($headers) { 
      // output header row (if at least one row exists) 
      $row = mysql_fetch_assoc($result); 
      if($row) { 
       fputcsv($fp, array_keys($row), ';'); 
       // reset pointer back to beginning 
       mysql_data_seek($result, 0); 
      } 
     } 

     while($row = mysql_fetch_assoc($result)) { 
      fputcsv($fp, $row, ';'); 
     } 

     fclose($fp); 
    }