在php中使用我自己的头从数组中创建和下载csv
我有一个非常简单的数组,我想把它导出到一个CSV文件中,这是我最常用的方法 但我希望我自己的头在文件的顶部,这也是一个数组,由我自己创建,如下所示-在php中使用我自己的头从数组中创建和下载csv,php,arrays,csv,export,Php,Arrays,Csv,Export,我有一个非常简单的数组,我想把它导出到一个CSV文件中,这是我最常用的方法 但我希望我自己的头在文件的顶部,这也是一个数组,由我自己创建,如下所示- $header = array( 'order_id' => 'order_id', 'firstname' => 'firstname',
$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\u to\u csv\u下载 然后,在写入导出数组之前,将头数组写入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);
}
请您发布您的代码,这可能有助于我们提供您的解决方案。