4

I have to create and write into a csv file. Now I tried with the following code:

header('Content-type: application/octet-stream');  
header('Content-disposition: attachment; filename="data.csv"');    
$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');

$fp = fopen('php://output', 'w+');  
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);  

It gives me my source file code also in the csv file? How can I solve this?

Laxman13
  • 5,226
  • 3
  • 23
  • 27

4 Answers4

1

header() needs to come after the array and fopen

try this:

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');
$fp = fopen('php://output', 'w+'); 
header('Content-type: application/octet-stream');  
header('Content-disposition: attachment; filename="data.csv"'); 
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);
JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29
1

Wrap it in <?php and ?> tags.

dkamins
  • 21,450
  • 7
  • 55
  • 59
1

Change the first header to header('Content-type: text/csv');

Yeroon
  • 3,223
  • 2
  • 22
  • 29
0

Try this:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

$data = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"');


$fp = fopen('php://output','w');
foreach ($data as $line) {
    fputcsv($fp, array_map('utf8_decode',array_values($line)), ',', '"');
}
fclose($fp);
Phong Tran
  • 36
  • 1
  • 3