从php导出数据到csv

时间:2013-09-25 13:40:28

标签: php csv

我正在使用此代码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);

首先,此程序无法处理localhost,但在server上正常工作。为什么呢?
其次,我得到的数据包含双重条目,即

+----+----+---------+---------+-----------+
| 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 个答案:

答案 0 :(得分:1)

mysql_fetch_array()更改为mysql_fetch_assoc()mysql_fetch_array()获取数据库结果的数字和关联数组。

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

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