After using several methods in the past to create CSV strings without using files (disk IO sucks), I finally decided it's time to write a function to handle it all. This function could use some cleanup, and the variable type test might be overkill for what is needed, I haven't thought about it too much.
Also, I took the liberty of replacing fields with certain data types with strings which I find much easier to work with. Some of you may not agree with those. Also, please note that the type "double" or float has been coded specifically for two digit precision because if I am using a float, it's most likely for currency.
I am sure some of you out there would appreciate this function.
<?php
function str_putcsv($array, $delimiter = ',', $enclosure = '"', $terminator = "\n") {
foreach ($array as $key => $value) $workArray[] = $value;
$returnString = ''; $arraySize = count($workArray); for ($i=0; $i<$arraySize; $i++) {
if (is_array($workArray[$i])) {
$returnString .= str_putcsv($workArray[$i], $delimiter, $enclosure, $terminator);
} else {
switch (gettype($workArray[$i])) {
case "NULL": $_spFormat = ''; break;
case "boolean": $_spFormat = ($workArray[$i] == true) ? 'true': 'false'; break;
case "integer": $_spFormat = '%i'; break;
case "double": $_spFormat = '%0.2f'; break;
case "string": $_spFormat = '%s'; break;
case "object":
case "resource":
default: $_spFormat = ''; break;
}
$returnString .= sprintf('%2$s'.$_spFormat.'%2$s', $workArray[$i], $enclosure);
$returnString .= ($i < ($arraySize-1)) ? $delimiter : $terminator;
}
}
return $returnString;
}
?>