dongxi2163 2015-01-19 07:12
浏览 207
已采纳

csv php mysql数据导出 - 所有数据都在一列中导出

I need Name,Given phonenumber mobile notes location to all be in separate columns on my csv export using the php script below. The current code exports all of the selected data in one column for each record. Thank you!

$result = mysql_query('SELECT who as "Name,Given" , phonenumber as "mobile", notes, location FROM `phpbb_phonelist` WHERE `activenumber` = 1'); 
if (!$result) die('Couldn\'t fetch records'); 
$num_fields = mysql_num_fields($result); 
$headers = array(); 
for ($i = 0; $i < $num_fields; $i++) 
{     
   $headers[] = mysql_field_name($result , $i); 
} 
$fp = fopen('php://output', 'w'); 
if ($fp && $result) 
{     
   header('Content-Type: text/csv');
   header('Content-Disposition: attachment; filename="phonelist.csv"');
   header('Pragma: no-cache');    
   header('Expires: 0');
   fputcsv($fp, $headers); 
   while ($row = mysql_fetch_row($result)) 
   {
      fputcsv($fp, array_values($row)); 
   }
die; 
  • 写回答

1条回答 默认 最新

  • duanshang9426 2015-01-19 07:13
    关注

    Use this code

    // output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    
    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');
    
    // output the column headings
    fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
    
    // fetch the data
    mysql_connect('localhost', 'username', 'password');
    mysql_select_db('database');
    $rows = mysql_query('SELECT field1,field2,field3 FROM table');
    
    // loop over the rows, outputting them
    while ($row = mysql_fetch_assoc($rows)) 
    
       fputcsv($output, $row);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题