简体   繁体   中英

PHP export array data into column of data in CSV

I'm trying to export nationality data into CSV. My nationality data are stored in an array. However, when i export it out, my CSV output show this error " : fputcsv() expects parameter 2 to be array" .:fputcsv() 期望参数 2 为数组” 。 Can I know how i can show my nationality data in a csv column?

my code:

$filename = "nationality_list.csv"; // Create file name
$array_nat = array('BANGLADESH','CAMBODIA','CHINESE','DUTCH','FILIPINO','FRENCH','GERMAN','INDIAN','INDONESIA','ITALY','JAPANESE','KOREAN','LITHUANIAN','MALAYSIA','MYANMAR','NEW ZEALAND','RUSSIAN','SINGAPOREAN','SRI LANKAN','THAILAND','UK','USA');
$f = fopen('php://memory', 'w');

$fields = array('Nationality_list');
        
fputcsv($f, $fields);
    
foreach($array_nat as $nat){
    fputcsv($f, $nat);
}

//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f)

Desired output in CSV

在此处输入图像描述

Try this:

fputcsv($f, [$nat]);

fputcsv expects an array because a row consists of n columns. 1 in your case:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM