我有一个非常简单的数组,我想将其导出到CSV文件中,这是我在这个帮助下完成的。如何从php脚本创建和下载CSV文件?
但我想在文件的顶部有我自己的头,这也是一个数组,我自己创建的,看起来像这样-
$header = array(
'order_id' => 'order_id',
'firstname' => 'firstname',
'lastname' => 'lastname',
'email' => 'email',
'telephone' => 'telephone',
'fax' => 'fax',
'product_id' => 'product_id',
'name' => 'name',
'model' => 'model',
'quantity' => 'quantity',
'price' => 'price',
'currency_value' => 'total',
'order_status' => 'order_status'
);
我原来的导出数组是-
Array
(
[0] => Array
(
[order_id] => 195
[firstname] => satyendra
[lastname] => singh
[email] => satyendra.singh43@gmail.com
[telephone] => 9818077908
[fax] =>
[product_id] => 7086
[name] => Bachini Casual Shoes 1511-Navy Blue
[model] => 1511-Navy Blue
[quantity] => 1
[price] => 499.00
[currency_value] => 499.00
[order_status] =>
)
[1] => Array
(
[order_id] => 196
[firstname] => satyendra
[lastname] => singh
[email] => satyendra.singh43@gmail.com
[telephone] => 9818077908
[fax] =>
[product_id] => 7086
[name] => Bachini Casual Shoes 1511-Navy Blue
[model] => 1511-Navy Blue
[quantity] => 1
[price] => 499.00
[currency_value] => 499.00
[order_status] =>
)
)
导出工作正常。我只想在原始数组的顶部添加这个头,这样当我导出这个头时,我就可以将数组的第一行作为csv文件中的头。任何一个物体都能有一些技巧来达到这个结果吗?
您可以尝试以下代码。
假设你使用的是你提到的代码-如何从php脚本创建和下载csv文件,请将$header数组作为第四个参数传递给函数array_to_csv_download。
然后,就在写入导出数组之前,将头数组写入csv文件。
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";",$header) {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
fputcsv($f, $header, $delimiter); // write $header array first to top of csv file
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}