把逗号作为分隔符导出到CSV在php中


put comma as separator in export to CSV in php

我必须在点击下载按钮的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>

和导出为csv代码如下。

<?php 
require_once 'dbconfig.php';
if(isset($_POST['btnDwld']))
{
    $filname = "UploadRateWeight-".date("d-M-Y-H:i:s");
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=$filname.csv");
header("Pragma: no-cache");
    function echocsv($fields)
{
    $separator = ',';
        foreach ($fields as $field) {
           if (preg_match('/''r|''n|,|"/', $field)) {
                   $field = '"' . str_replace('"', '""', $field) . '"';
              } // end if
           echo $field.$separator;
        }   // end foreach
    echo "'r'n";
}
    $content = '';
    $title = '';
    $title = array('0'=>'head part1','1'=>'head part2','2'=>'head part3','3'=>'head part4','4'=>'head part5');
    $headerr = echocsv($title);
    $sql = "SELECT * FROM table_name";
    $query = mysql_query($sql);
    while($rs = mysql_fetch_array($query)) {
        $name = $rs["name"];
        $line = array('0'=>$name,'1'=>'','2'=>'','3'=>'','4'=>'');
        echocsv($line);
        //$content .= "'n";
    }
}

. csv文件的输出如下所示:

head
----------
name1
name2
name3

正如你所看到的,我将第一列的名称设置为"head part1",但它将显示为"head",因为它以空格作为分隔符。

第二列的名称是这个。

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

和第三个列名接受这个。

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

等等。那么如何使用逗号作为分隔符,而在php导出CSV文件??

请勿手动编写csv文件。使用内置函数

。http://uk3.php.net/manual/en/function.fputcsv.php

<?php
$delimiter = ',';
$enclosure = '"';
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
    fputcsv($fp, $fields, $delimiter, $enclosure);
}
fclose($fp);
?>

上面的代码将创建一个名为file.csv的文件,其中包含您的数据。如果您想将此文件作为CSV文件发送给用户,您可以这样做:

<?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');
?>

或者,您可以直接发送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";
}
?>