Puvi Puvi - 1 year ago 54
PHP Question

csv file is not downloading within for loop

Comparing two multidimensional array and get the result by matching values. How to create and download the csv file for those respective values. I have tried this code below

$mycsvfile_result = array();
foreach ($mycsvfile as $arr1)
{
foreach ($mycsvfile_log as $arr2)
{
if($arr2[2] == $arr1[0])
{
$mycsvfile_result[] = array($arr2[2], $arr2[7]);
}
}
}


tried code 1 for fputcsv

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$fp = fopen('php://output', 'w');
$data=$mycsvfile_result;
foreach ( $data as $line )
{
fputcsv($fp, $line);
}
fclose($fp);
exit();


tried code 2 for fputcsv

$csv = "col1,col2 \n";//Column headers
foreach ($mycsvfile_result as $record)
{
$csv.= $record[0].','.$record[1]."\n"; //Append data to csv
}
$csv_handler = fopen ('demo.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
echo 'Data saved to demo.csv';


The above code 1 results in

id1,email1 id2,email2 id3,email3


The above code 2 results in

col1,col2 id1,email1 id2,email2 id3,email3 Data saved to demo.csv

Answer Source

I'm working in linux machine, I forget to give the folder permission to upload the csv file. After giving folder permission it works like a charm :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download