Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to export string w/ commas in it properly into a CSV file

Tags:

php

mysql

csv

EDIT: Copied wrong part of function into this question, below is the appropriate one.

$values = mysql_query("SELECT lname, fname, email, dtelephone, etelephone, contactwhen, thursday, 
friday, saturday, sunday, monday, comments FROM volunteers_2009 WHERE venue_id = $venue_id");

while ($rowr = mysql_fetch_row($values)) {
    for ($j=0;$j<$i;$j++) {
        $csv_output .= $rowr[$j].", ";
    }
    $csv_output .= "\n";
}

I have comments that may have a comma in it, and even double quotes, when it has a comma in the comment field, it throws off the entire csv file.

The code below is how it loads the data into the csv string, to put into a csv file.

How do I get it to export the comments field data properly?

like image 339
Brad Avatar asked Apr 21 '09 00:04

Brad


2 Answers

You should check out fputcsv(). There are some useful comments there as well.

int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' 
    [, string $enclosure = '"' ]] )

fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.

like image 52
sshow Avatar answered Oct 10 '22 12:10

sshow


Enclose the field in double quotes. Double up any embedded double quotes.

ordinary field,"field with , in it","field with double double quote ("""")"

Note that this is very, very close to the question Dealing with commas in a CSV file

like image 45
Jonathan Leffler Avatar answered Oct 10 '22 11:10

Jonathan Leffler