doujing2017 2010-03-01 08:01
浏览 79
已采纳

PHP CSV导出功能

I am trying to export data from my MySQL database to multiple CSV files and then GZIP them.

I have a couple of problems which make exporting it to a CSV file complicated ...

  1. Several fields (10) need to be in 1 CSV file
  2. Other fields (multiple!) are serialized and need to be exported into a different CSV file with two other non serialized fields included in that CSV file.

What I want to do is have all those CSV files created in a gzip file ... Here's what I have so far! What happens it the user checks different check boxes with which file they want to export. Then its passed to this file where each file has a different SELECT query and field names. I haven't even started to deal with the serialized data yet ... I have no idea how I am going to do that. It then returns the CSV file and I place that file into an array which is waiting to be exported into a gzip ... don't even know if I can do that.

Any suggestions or help would be greatly appreciated!

$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 .="
";

 // Add all values in the table
 while ($l = mysql_fetch_array($rsSearchResults)) {
 for ($i = 0; $i < $columns; $i++) {
 $out .='"'.$l["$i"].'",';
 }
 $out .="
";
 }
 return $out;
 }
exit; 
  • 写回答

2条回答 默认 最新

  • dongshan4878 2010-03-01 08:17
    关注

    Check out the fputcsv() function. It will handle quotes/escaping much better than what you have.

    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条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用