iamjonesy
iamjonesy

Reputation: 25122

Add Quotes to CSV Export

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.

Upvotes: 5

Views: 10183

Answers (2)

Álvaro González
Álvaro González

Reputation: 146640

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.

Upvotes: 7

user1646111
user1646111

Reputation:

This is just normal, if you create CSV file using Excel and enclose one cell with double quota, then, it will added others to the source file, for example:

This is how CSV appears in Microsoft Office Excel 2007:

"
""
"""
""""
"""""

Source code:

"""",
"""""",
"""""""",
"""""""""",
"""""""""""",

Then nothing goes wrong, as you can see the first example in the documentation:

<?php

$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);
}

fclose($fp);
?> 

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

Upvotes: -1

Related Questions