Voting

: max(two, nine)?
(Example: nine)

The Note You're Voting On

drew at zitnay dot com
20 years ago
[EDIT BY danbrown AT php DOT net: This is a revised function with a few bugfixes and improvements done by this author. The original function example was written by arthur AT mclean DOT ws, and rewritten between by arthur AT korn DOT ch.]

- 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:

<?php
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

<< Back to user notes page

To Top