将报价添加到CSV导出 [英] Add Quotes to CSV Export

查看:83
本文介绍了将报价添加到CSV导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fputcsv将数据导出到CSV文件.我有正在写的字符串,但是我有一个要求将数据用双引号引起来.

foreach ($orderDetails['lines'] as $line) {
     fputcsv($orderImportCsv, $line);
}

这在编辑器中打开时会创建以下内容(崇高)

L,M3344,,100

L,M3356,,50

我需要将每个字段都用双引号引起来.

所以我尝试了这个:

foreach ($lines as &$line) {
    foreach ($line as &$column) {
        $column = '"' . $column . '"';
    }
}

因此,本质上,这应该遍历每行字段并将其包装为".但是运行后,我得到以下输出:

"p","L","L","M3344","M3344","100"

"p","L","L","M3356","M3356","50"

现在在变量周围放置了两组双引号!

有更好的方法吗?

更新

我知道fputcsv有两个可选参数.分隔符和外壳.但是,我相信附件默认为".但只有在将字符串拆分为单独的单词时.

解决方案

由于您自己插入了附件,因此必须指示PHP不使用任何附件.似乎没有记录在案的方法,但是使用空格似乎可行:

<?php
foreach($orderDetails['lines'] as $line){
    foreach ($line as &$column) {
        $column = '"' . $column . '"';
    }
    unset($column);

    fputcsv($orderImportCsv, $line, ',', ' ');
}

或者您可以避免 fputcsv()自己编写所有内容.

I'm exporting data to a CSV file using fputcsv. I have strings that are being written however I have a requirement that the data is wrapped in double quotes.

foreach ($orderDetails['lines'] as $line) {
     fputcsv($orderImportCsv, $line);
}

This creates the following when opened in an editor (sublime)

L,M3344,,100

L,M3356,,50

I need to have each of these fields wrapped in double quotes.

So I have tried this:

foreach ($lines as &$line) {
    foreach ($line as &$column) {
        $column = '"' . $column . '"';
    }
}

So essentially this should go through each lines fields and wrap it in "". However after running that I get the following output:

"""L""","""M3344""","""""","""100"""

"""L""","""M3356""","""""","""50"""

It's now putting 2 sets of double quotes around the variable!

Is there a better way to do this?

UPDATE

I know fputcsv has two optional parameters. Delimiter and enclosure. However I believe enclosure defaults to "" but only when the string is split into separate words.

解决方案

Since you insert the enclosure yourself, you have to instruct PHP to use none. There doesn't seem to be a documented way to do it, but using a space seems to work:

<?php
foreach($orderDetails['lines'] as $line){
    foreach ($line as &$column) {
        $column = '"' . $column . '"';
    }
    unset($column);

    fputcsv($orderImportCsv, $line, ',', ' ');
}

Or you can just avoid fputcsv() and compose everything yourself.

这篇关于将报价添加到CSV导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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