note 47606 added to function.fputcsv
| From: | drew at zitnay dot com | Date: | Mon, 22 Nov 2004 17:42:36 +0000 |
| Subject: | note 47606 added to function.fputcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-80884@lists.php.net to get a copy of this message | ||
I found the following problems with the below function:
- when calling str_replace(), you must assign $cell the return value or nothing gets saved
- when using strchr(), you should explicitly check !== FALSE, or it'll treat a return value of
0 (found the character at string position 0) as FALSE
- Excel seems to quote not only fields containing commas, but fields containing quotes as well, so
I've added another strchr() for quotes; I'm not saying Microsoft knows the correct way for
sure, but it seems reasonable to me
- the original function put a space after each comma; that might be legal, I don't know, but
I've never seen it (and I don't think it is, because then how would you indicate you
wanted a field to start with a space other than by quoting it?)
- the original function didn't correctly return the length of the data outputted
Here's the function, fixed up a bit:
function fputcsv($handle, $row, $fd=',', $quot='"')
{
$str='';
foreach ($row as $cell) {
$cell=str_replace(Array($quot, "\n"),
Array($quot.$quot, ''),
$cell);
if (strchr($cell, $fd)!==FALSE || strchr($cell, $quot)!==FALSE) {
$str.=$quot.$cell.$quot.$fd;
} else {
$str.=$cell.$fd;
}
}
fputs($handle, substr($str, 0, -1)."\n");
return strlen($str);
}
Drew
----
Manual Page -- http://www.php.net/manual/en/function.fputcsv.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47606
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47606&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47606&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47606&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47606&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47606&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47606&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47606&report=yes
Search -- http://master.php.net/manage/user-notes.php