467,104 Members | 1,035 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,104 developers. It's quick & easy.

Writing array to csv string

Hey all,

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?

Thanks,

Adam
Jul 17 '05 #1
  • viewed: 28859
Share:
3 Replies
Adam Levenstein wrote:
Hey all,

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?

Thanks,

Adam


Have a look at the implode function, that should get you started.

HTH,

Derek
Jul 17 '05 #2
Adam Levenstein wrote:
Hey all,

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?

Thanks,

Adam


Something like the following should work...

$csv='';
foreach($array as $v)
$csv.=', \''.addslashes($v).'\'';
$cvs=substr($csv,2);

--
Justin Koivisto - sp**@koivi.com
PHP POSTERS: Please use comp.lang.php for PHP related questions,
alt.php* groups are not recommended.
Jul 17 '05 #3
cl*****@yahoo.com (Adam Levenstein) wrote in message
news:<a3**************************@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
Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by rob | last post: by
3 posts views Thread by Joshua Russell | last post: by
2 posts views Thread by melanieab | last post: by
3 posts views Thread by Bry | last post: by
2 posts views Thread by simonc | last post: by
9 posts views Thread by jerry.upstatenyguy@gmail.com | last post: by
16 posts views Thread by billsahiker@yahoo.com | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.