简体   繁体   English

从php导出数据到csv

[英]export data to csv from php

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 . 首先,该程序不能在我的localhost但可以在server正常运行。 Why? 为什么?
Second, the data I'm getting contains double entries, ie, 其次,我要获取的数据包含重复项,即

+----+----+---------+---------+-----------+
| 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 |
+----+----+---------+---------+-----------+----------+-------------+------------+

Change mysql_fetch_array() to mysql_fetch_assoc() . mysql_fetch_array()更改为mysql_fetch_assoc() mysql_fetch_array() fetches both a numeric and associative array of the database results. mysql_fetch_array()获取数据库结果的数字数组和关联数组。

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM