PHP导出csv文件,特定行结束

时间:2014-07-11 21:54:47

标签: php csv

我有一个csv文件,我使用以下代码读取并保存为输出文件:

CSV内容:

10038,"Service, Inc.",loten,4u@att.net,9951,xxx,6321
10041,Roadsi deInc.,Kgel,gel1980@gmail.com,1101,xxx,7967
10042,Rang LLC,Resgers,resranger85@yahoo.com,2073,4611,xxx


<?php
    $csv_filename = "output.csv";
    $fp = fopen($csv_filename, "w");
    if (($handle = fopen(__DIR__.'/test.csv', "r")) !== FALSE && $fp) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $data_row = array(
                    $data[0],
                    $data[1],
                    $data[2],
                    $data[3],
                    $data[4],
                    $data[5]
            );
            fputcsv($fp, $data_row, "|");
        }
    }
    fclose($handle);
    fclose($fp);

我得到的结果如下:

10038|"Service, Inc."|loten|4u@att.net|9951|xxx
10041|"Roadsi deInc."|Kgel|gel1980@gmail.com|1101|xxx
10042|"Rang LLC"|Resgers|resranger85@yahoo.com|2073|4611

如何在字符串中有空格时删除fputcsv函数添加的引号,如何在csv输出的每一行添加0d0a结尾?

1 个答案:

答案 0 :(得分:2)

报价由fputcsv添加,尝试fputsjoin

<?php
    $csv_filename = "output.csv";
    $fp = fopen($csv_filename, "w");
    if (($handle = fopen(__DIR__.'/test.csv', "r")) !== FALSE && $fp) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $data_row = array(
                    $data[0],
                    $data[1],
                    $data[2],
                    $data[3],
                    $data[4],
                    $data[5]
            );
            fputs($fp, join("|", $data_row)."\r\n";
        }
    }
    fclose($handle);
    fclose($fp);