如何在php中组织可下载的csv文件

时间:2012-11-30 12:10:48

标签: php mysql csv

我正在做的是允许我的客户在数据库中下载所有订单的CSV文件。我可以做,但我似乎无法弄清楚如何组织该文件,以便信息在文件本身清晰易懂。

以下是我的工作代码,用于创建要下载的文件:

$today = date("d-m-Y");
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=orders_' . $today . '.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Product ID & Qty','First Name', 'Last Name', 'Total Spent', 'Payment Date'));

// fetch the data
include('../storescripts/connect_to_mysql.php');
$rows = mysql_query('SELECT product_id_array, first_name, last_name, mc_gross, payment_date FROM transactions ');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

使用上面列出的标题创建列,但几乎所有信息都被挤入第一列,其余信息只是分布在其他列上。它看起来一团糟,对任何人都没有多大意义。

我想知道是否有办法强制哪一行数据进入每一列。 提前致谢。

1 个答案:

答案 0 :(得分:1)

默认情况下,当Excel读取CSV时,它不会自动展开所有列,因此数据看起来好像CSV内容本身有问题,实际上您只需要配置Excel或手动展开它们