将逗号作为分隔符导出到php中的CSV文件中 [英] put comma as separator in export to CSV in php

查看:250
本文介绍了将逗号作为分隔符导出到php中的CSV文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击下载按钮后,我必须以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文件.使用内置功能.<​​/p>

例如 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";
}

?>

希望这会有所帮助.

I have to get mysql data in a CSV file on click of download button. The below code exports data successfully but adds space as separator. But I need comma to be separator not space, As there are space in mysql data and also on static header of csv file.

HTML code is below.

<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>

And export to csv code is below.

<?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";
    }
}

The out put in a .CSV file looks like below.

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

As you can see I have put 1st colum name as 'head part1' but it will show like 'head' as its taking space as separator.

So second column name takes this.

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

and third column name takes this.

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

and so on. So how to use a comma to be separator while exporting CSV file in php ??

解决方案

Don't write csv file's manually. Use the built in function.

e.g. 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);
?>

The above code will create a file called file.csv with your data on it. If you then want to send this file to the user as a CSV file, you can do this:

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

?>

Alternatively, you can send the CSV file to download directly without creating the file on server like this:

<?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";
}

?>

Hope this helps.

这篇关于将逗号作为分隔符导出到php中的CSV文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆