View Single Post

  #4 (permalink)  
Old 07-09-2004
Nikolai Chuvakhin
 
Posts: n/a
Default Re: Writing array to csv string

cleon42@yahoo.com (Adam Levenstein) wrote in message
news:<a32e730c.0407070759.7d74c5db@posting.google. com>...
>
> I have need to take an array of strings from a form and write it to a
> string (not a file) in csv format. Is there a quick n' easy way of
> doing this?


Sure. The easy way is to use the implode() function, but this will
create a problem if one or more of your array fields is a text
containing a comma. So you need to enclose text fields.

Assuming your form is submitted via POST, here's what you can do:

$csvstring = '';
foreach ($_POST as $value) {
if ($csvstring <> '') {
$csvstring .= ',';
}
if (is_numeric($value)) {
$csvstring .= $value;
} else {
$csvstring .= "'$value'";
}
}

Yet another alternative is to use implode, but enclose ALL fields:

$csvstring = "'" . implode("','", $_POST) . "'";

Cheers,
NC
Reply With Quote