Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created December 17, 2020 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/54581a20d80139290faffc8430618bfd to your computer and use it in GitHub Desktop.
Save kobus1998/54581a20d80139290faffc8430618bfd to your computer and use it in GitHub Desktop.
generate a csv using a single function
<?php
/**
* @var array[]
* @var string
* @var string
*/
function csv($aCsv, $sDelimiter = ',', $sLineBreak = "\n")
{
return implode($sLineBreak, array_map(
function ($aLine) use ($sDelimiter) {
$aLine = array_map(function ($s) {
$s = str_replace('"', '', $s); // replace all double quotes
if (preg_match("/[a-zA-Z]/", $s)) { // check letters in the string
return "\"{$s}\""; // quote the line
}
return $s;
}, $aLine);
return str_replace(["\r\n", "\n"], '', implode($sDelimiter, $aLine)); // replace all line ends
},
$aCsv
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment