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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置