簡體   English   中英

從php導出數據到csv

[英]export data to csv from php

我正在使用這里提到的代碼。

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

mysql_fetch_array()更改為mysql_fetch_assoc() mysql_fetch_array()獲取數據庫結果的數字數組和關聯數組。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM