tags:

views:

44

answers:

2

So, my code generates a CSV file using PHP's built-in fputcsv function.

For the delimiter, I use ',' (a comma).
For the enclosure, I use '"' (a double-quote).

However, when I try something like

fputcsv($file,array('a','b',"long string, with commas",NULL,''),',','"');

it outputs

a,b,"long string, with commas",,

but I would like it to output

"a","b","long string, with commas","",""

Is there an easy way to deal with this, or would I have to write a replacement for fputcsv?

+1  A: 

This is not usually a problem for CSV files.

fputcsv puts quotes around the value if it would be ambiguous. For example,

a,b,"long string, with commas",,

is not ambiguous, but,

a,b,long string, with commas,,

is, and will in most (read: all) cases be interpreted by the CSV reader as having more than 5 fields.

CSV parsers will accept string literals even without quotes around them.

If you want quotes around the values anyway, the following snippet would do that. It doesn't escape quotes inside the string - that exercise is left to the reader:

$row = '"' . implode('", "', $rowitems) . '"';

You would want to put this in a loop for all your rows.

Thomas O
Yeah, I know about the ambiguity, but it's really the empty parts that I need wrapped in quotes. I can live without the non-empty parts being wrapped (except for the ambiguous ones, of course).
Austin Hyde
Your comment is confusing.You want the empty parts wrapped in quotes but the non-empty parts could go without wrapping? What do you mean. The snippet posted will wrap all in quotes which should work with all CSV parsers.
Thomas O
Never mind. I was a tad confused. Yes, this should work. Thanks.
Austin Hyde
A: 

Any reason you can't str_replace(',,',',"",',$output); ? You'd also have to see if the last or first character is a comma and if so, replace the comma with ,""

methodin
That was actually my first thought, but then I'd have to intercept the file-write to a string. D:
Austin Hyde
Ah yes. Completely forgot to think about what fputcsv actually does hah. You are better off writing your own function that escapes the data and outputs it using fputs or fwrite.
methodin