csv php mysql 数据导出 - 所有数据都导出到一列中 [英] csv php mysql data export - all data is being exported in one column

查看:39
本文介绍了csv php mysql 数据导出 - 所有数据都导出到一列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用下面的 php 脚本在我的 csv 导出中将姓名、给定电话号码移动笔记位置都放在单独的列中.当前代码为每条记录导出一列中的所有选定数据.谢谢!

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; 

推荐答案

使用此代码

// 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);

这篇关于csv php mysql 数据导出 - 所有数据都导出到一列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆