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?
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);
用<?php
和?>
标签包装它。
将第一个标题更改为header('Content-type: text/csv');
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);
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.