我必须创建并写入csv文件。现在我尝试使用以下代码:
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);
它还在csv文件中提供了我的源文件代码?我该如何解决这个问题?
答案 0 :(得分:2)
将其包裹在<?php
和?>
标记中。
答案 1 :(得分:2)
header()需要在数组和fopen
之后试试这个:
$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);
答案 2 :(得分:1)
将第一个标题更改为header('Content-type: text/csv');
答案 3 :(得分:0)
试试这个:
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);