PHP CSV导出功能

时间:2010-03-01 08:01:07

标签: php mysql

我正在尝试将数据从我的MySQL数据库导出到多个CSV文件然后GZIP。

我有几个问题导致将其导出为CSV文件很复杂......

  1. 多个字段(10)需要位于1个CSV文件中
  2. 其他字段(多个!)已序列化,需要导出到另一个CSV文件中,该文件中包含另外两个非序列化字段。
  3. 我想要做的是在gzip文件中创建所有这些CSV文件......这是我到目前为止所拥有的!如果用户检查了要导出哪个文件的不同复选框,会发生什么。然后将其传递给此文件,其中每个文件都有不同的SELECT查询和字段名称。我还没有开始处理序列化数据......我不知道我将如何做到这一点。然后它返回CSV文件,我将该文件放入一个等待导出到gzip的数组中......甚至不知道我是否可以这样做。

    任何建议或帮助将不胜感激!

    $files = array();
    
    if(in_array("general", $_POST['exportid'])){
     $files[] = CSVoutput("SELECT timestamp, id, monday, tuesday, wednesday, thursday, friday, saturday, sunday, records, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 23, 24 FROM hourly", array(timestamp, id, monday, tuesday, wednesday, thursday, friday, saturday, sunday, records, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 23, 24));
    }
    
    function CSVoutput($query, $fields){ 
     $rsSearchResults = mysql_query($query) or die(mysql_error());
    
     $out = '';
     $columns = count($fields);
    
     // Put the name of all fields
     for ($i = 0; $i < $columns; $i++) {
     $l= $fields[$i];
     $out .= '"'.$l.'",';
     }
     $out .="\n";
    
     // Add all values in the table
     while ($l = mysql_fetch_array($rsSearchResults)) {
     for ($i = 0; $i < $columns; $i++) {
     $out .='"'.$l["$i"].'",';
     }
     $out .="\n";
     }
     return $out;
     }
    exit; 
    

2 个答案:

答案 0 :(得分:2)

查看fputcsv()函数。它会比你拥有的更好地处理报价/逃避。

res = query_result
row = fetch array from res

handle/remove serialized columns in row
fputcsv(row array keys)
fputcsv(row values)

while(row = fetch from res)
    handle/remove serialized columns in row
    fputcsv(row values)

答案 1 :(得分:-1)

您可能有理由这样做,但我只是想提一下SELECT ... INTO OUTFILE将select的结果导出到csv文件中。

您还可以指定字段的分隔方式等。所以你可能想尝试一下。

另见本页(向下滚动至SELECT INTO OUTFILE) http://dev.mysql.com/doc/refman/5.1/en/select.html

如果您需要手动执行此操作,请忽略我的评论。

相关问题