使用PHP从MySql数据库生成Excel表格

我是PHP新手。 我正在使用下面的代码来使用PHP从Mysql数据库生成一个Excel工作表。

<?php include("../Connection/Connection.php"); $db_con=new Connection(); $db_con->get_connection(); //Opens a database connection. This function is contained in the Connection.php which is included above. $result = mysql_query("SELECT * FROM country"); if (!$result) die('Couldn\'t fetch records'); $num_fields = mysql_num_fields($result); $headers = array(); for ($i = 0; $i < $num_fields; $i++) { $headers[] = mysql_field_name($result , $i); } $fp = fopen('php://output', 'w'); if ($fp && $result) { header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="export.csv"'); header('Pragma: no-cache'); header('Expires: 0'); fputcsv($fp, $headers); while ($row = mysql_fetch_array($result)) { fputcsv($fp, array_values($row)); } die; } ?> 

上面的代码正在工作,它会生成指定的文件export.csv但问题是它会在这个文件中两次从MySql生成每一列。 换句话说,每一列都重复两次(显示的标题不会重复)。 这段代码有什么问题? 应该做什么样的改变才能显示每一列?

改用mysql_fetch_row

mysql_fetch_array用BOTHstring索引和数字索引获取一个数组,所以每个值都被提取两次。 你的代码可以用于mysql_fetch_assocmysql_fetch_row