duaevb1511 2013-09-25 13:40
浏览 77
已采纳

从php导出数据到csv

I'm using this code as mentioned here.

$file = date('dmY-His');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=visitors-$file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$sql = "select id, ip, server, time, date from visitors";
$res = mysql_query($sql);
$data = array();
$data[] = array('id', 'ip', 'server', 'time', 'date');
while ($row = mysql_fetch_array($res)) {
    $data[] = array_values($row);
}

$output = fopen("php://output", "w");
foreach ($data as $val) {
    fputcsv($output, $val);
}
fclose($output);

First of all, this program in not working on my localhost but works fine on server. Why?
Second, the data I'm getting contains double entries, i.e.,

+----+----+---------+---------+-----------+
| id | ip | server  | time    | date      |
+----+----+---------+---------+-----------+
| 1  | 1  | :::1    | :::1    | server1   | server1  | 10:00:00 am | 12-12-2012 |
+----+----+---------+---------+-----------+----------+-------------+------------+
| 2  | 2  | :::2    | :::2    | server2   | server2  | 10:15:00 am | 13-12-2012 |
+----+----+---------+---------+-----------+----------+-------------+------------+
  • 写回答

1条回答 默认 最新

  • duanba3707 2013-09-25 13:41
    关注

    Change mysql_fetch_array() to mysql_fetch_assoc(). mysql_fetch_array() fetches both a numeric and associative array of the database results.

    while ($row = mysql_fetch_array($res)) {
    

    to

    while ($row = mysql_fetch_assoc($res)) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法