Skip to content

Instantly share code, notes, and snippets.

@destinydriven
Created August 3, 2018 00:10
Show Gist options
  • Save destinydriven/2ccda3b43a963161bc36c80f8560caad to your computer and use it in GitHub Desktop.
Save destinydriven/2ccda3b43a963161bc36c80f8560caad to your computer and use it in GitHub Desktop.
/**
* Generates a single row in a csv from an array of
* data by writing the array to a temporary file and
* returning it's contents
*
* @param array $row Row data
* @return mixed string with the row in csv-syntax, false on fputcsv or fwrite failure
*/
protected function _generateRow($row = null) {
static $fp = false;
if ($fp === false) {
$fp = fopen('php://temp', 'r+');
if ($this->viewVars['_bom']) {
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
}
if ($this->viewVars['_setSeparator']) {
fwrite($fp, "sep=" . $this->viewVars['_delimiter'] . "\n");
}
} else {
ftruncate($fp, 0);
}
if ($row === false || $row === null) {
return '';
}
$delimiter = $this->viewVars['_delimiter'];
$enclosure = $this->viewVars['_enclosure'];
$newline = $this->viewVars['_newline'];
$row = str_replace(array("\r\n", "\n", "\r"), $newline, $row);
if ($enclosure === false) {
if (fwrite($fp, implode($row, ',')."\n") === false) {
return false;
}
} else {
if (fputcsv($fp, $row, $delimiter, $enclosure) === false) {
return false;
}
}
rewind($fp);
$csv = '';
while (($buffer = fgets($fp, 4096)) !== false) {
$csv .= $buffer;
}
$eol = $this->viewVars['_eol'];
if ($eol !== "\n") {
$csv = str_replace("\n", $eol, $csv);
}
return $csv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment