Skip to content

Instantly share code, notes, and snippets.

@drew887
Last active March 29, 2018 02:59
Show Gist options
  • Save drew887/b83fb1b846b76271b7cca29d48f3a21e to your computer and use it in GitHub Desktop.
Save drew887/b83fb1b846b76271b7cca29d48f3a21e to your computer and use it in GitHub Desktop.
My str_putcsv implementation, probably could be better but behaves the same as fputcsv, except it always wraps with ""
<?php
/**
* Takes an array and returns a string of csv in the same format that fputcsv
* would; but every one is wrapped rather than just ones that require it
* because str_getcsv will still parse itcorrectly
*
* NOTE: That currently str_getcsv and fgetcsv fail with encaser being any
* value other than " this holds for if its encoded with fputcsv as well.
*
* @param array $fields an array of string values to encode in csv
* @param character $delimiter the character to use instead of a comma
* @param character $encaser the character wrap itself around, this is how
* fputcsv "escapes" the quotes or whatever value you need escaped that the
* input might not have escaped. CURRENTLY MUST BE "
* @param character $escaper the character to use as an escape, prevents the next
* character from being encased
* @return string the formatted string
*/
function str_putcsv(array $fields, $delimiter = ",", $encaser = '"', $escaper = '\\') {
$result = "";
foreach ($fields as $field) {
//rather than search the string everytime incase it might contain various characters, just wrap it anyway
//php does it in C but we ain't got that kinda speed
$part = '"';
$chars = \str_split($field);
$size = \count($chars);
for ($ctr = 0; $ctr < $size; $ctr++) {
//If we need to encase and the prev one isn't the escape character
if (($chars[$ctr] === $encaser) && ($ctr === 0 || $chars[$ctr - 1] !== $escaper)) {
$part .= $encaser;
}
$part .= $chars[$ctr];
}
$part .= '"' . $delimiter;
$result .= $part;
}
//chop off the last delimiter
return \substr($result, 0, -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment