Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中导出为CSV时将逗号作为分隔符_Php_Csv_Export To Csv - Fatal编程技术网

在php中导出为CSV时将逗号作为分隔符

在php中导出为CSV时将逗号作为分隔符,php,csv,export-to-csv,Php,Csv,Export To Csv,我必须在点击下载按钮时获得CSV文件中的mysql数据。下面的代码成功导出数据,但添加了空格作为分隔符。但我需要逗号作为分隔符,而不是空格,因为mysql数据和csv文件的静态头上都有空格 下面是HTML代码 <form name="downloadform" id="downloadform" action="exportcsv.php" method="POST"> <div style="font-weight:bold; line-height:30px;" clas

我必须在点击下载按钮时获得CSV文件中的mysql数据。下面的代码成功导出数据,但添加了空格作为分隔符。但我需要逗号作为分隔符,而不是空格,因为mysql数据和csv文件的静态头上都有空格

下面是HTML代码

<form name="downloadform" id="downloadform" action="exportcsv.php" method="POST"> 
<div style="font-weight:bold; line-height:30px;" class="TableContainer">
        <label>Download CSV Format:</label>
        <button class="blue" name="btnDwld" id="btnDwld" type="submit">Download</button>
</div>
</form>
正如你们所看到的,我把第一个柱的名字命名为“头部分1”,但它会像“头”一样显示,因为它以空格作为分隔符

第二列的名字就是这个

part1,head
----------
part2,head
----------
第三列的名字就是这个

part1,head
----------
part2,head
----------

等等。所以,在php中导出CSV文件时,如何使用逗号作为分隔符???

不要手动写入CSV文件。使用内置函数

e、 g

或者,您可以直接发送CSV文件进行下载,而无需在服务器上创建文件,如下所示:

<?php

// mini-config
$delimiter = ',';

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

// Send headers
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Output csv data
foreach ($list as $row) {
    echo implode($delimiter, $row) . "\r\n";
}

?>

不要重新发明轮子,功能
fputcsv
永远存在。是的。我在SO中看到了这个函数。但是我很困惑“fopen()”会打开一个文件还是创建一个文件?我想在单击下载时创建一个包含数据的文件。抱歉,我以为您正在尝试创建该文件。请参阅更新的答案。否,我需要的答案的最后一块CSV文件不创建文件直接下载不起作用。你也可以检查这个。只需编辑数组并在值中添加空格即可。就像“aa a”,“b bb”,“cc cc”。你可以看到,它不起作用。你说它不起作用是什么意思?如果需要直接写入输出,
fopen('php://output“,”w“
。仍然不需要手动划界。
<?php

// Send the generated csv file to the browser as a download
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');

?>
<?php

// mini-config
$delimiter = ',';

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

// Send headers
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Output csv data
foreach ($list as $row) {
    echo implode($delimiter, $row) . "\r\n";
}

?>