我正在创建一个CSV文件,其数据是从MySQL数据库中提取的。我成功地从查询中分离和组织它,它正在写入csv文件。我可以在服务器端打开它,看看我想要的数据。
但是,当我从网站下载到客户端计算机时,csv文件不会在任何电子表格程序中自动打开。强制时,会弹出一条错误消息。在记事本和Notepad ++中查看它显示乱码数据,在某些OpenOffice程序中打开它显示空白。
我已经尝试过application / csv和text / csv。我尝试使用fputcsv而不是fwrite,但得到了相同的结果。
function generateCSV($list){
$file = fopen("data.csv", "w");
mysql_connect();
mysql_select_db();
$sql = "SELECT DISTINCT(name) FROM statistics";
$result = mysql_query($sql);
$names = array();
while($pull = mysql_fetch_assoc($result))
$names[] = $pull;
$stats = array();
$sets = array();
for($i = 0; $i < count($names); $i++){
$sql = "SELECT name, facebook, twitter ";
$sql .= "FROM statistics ";
$sql .= "WHERE name='" . $names[$i]['name'] . "' ";
$sql .= "ORDER BY date ASC";
$result = mysql_query($sql);
$stats[$names[$i]['name']] = '';
while($pull = mysql_fetch_assoc($result))
$stats[$names[$i]['name']] .= $pull['facebook'] . ', ' . $pull['twitter'] . ', ';
}
mysql_close();
for($i = 0; $i < count($names); $i++){
$txt = trim($names[$i]['name']) . ', ' . $stats[$names[$i]['name']];
$txt = substr($txt, 0, -2);
$txt = $txt . "\n";
fwrite($file, $txt);
}
fclose($file);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=data.csv");
header("Pragma: no-cache");
header("Expires: 0");
}
如果我回显$ txt
,这就是数据的样子Matisse Reid, 94, 10, 94, 10, 94, 10, 94, 10
Rev. Eugene Beard, 0, 2, 0, 2, 0, 2, 0, 2
Haley Spitznagel, 0, 0, 0, 0, 0, 0, 0, 0
Kelly Nerger, 0, 0, 0, 0, 0, 0, 0, 0
Braden Hagood, 0, 0, 0, 0, 0, 0, 0, 0
Cassidy Yeager, 0, 0, 0, 0, 0, 0, 0, 0
Anna Conover, 0, 0, 0, 0, 0, 0, 0, 0
Eveline Cameron, 0, 0, 0, 0, 0, 0, 0, 0
Wendy Brown, 0, 0, 0, 0, 0, 0, 0, 0
Don Maicki, 0, 0, 0, 0, 0, 0, 0, 0
Madison MacDonald, 0, 0, 0, 0, 0, 0, 0, 0
Bill Suit, 0, 4, 0, 4, 0, 4, 0, 4
Isaias Hernandez, 0, 0, 0, 0, 0, 0, 0, 0
Carl Firetto, 0, 0, 0, 0, 0, 0, 0, 0
Barbara Wright, 0, 0, 0, 0, 0, 0, 0, 0
Bill Hawse, 4, 0, 4, 0, 4, 0, 4, 0
Megan Jones, 0, 0, 0, 0, 0, 0, 0, 0
Valerie Cousar, 13, 0, 13, 0, 13, 0, 14, 0
Agnes Downing, 0, 0, 0, 0, 0, 0, 0, 0
Jamie Moran, 0, 0, 0, 0, 0, 0, 60, 0
George Chagaris, 0, 0, 0, 0, 0, 0, 0, 0
Kelly Finley, 0, 2, 0, 2, 0, 2, 0, 2
Tom Roundtree, 0, 0, 0, 0, 0, 0, 0, 0