Skip to content

Instantly share code, notes, and snippets.

@hisorange
Created May 29, 2018 20:35
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 hisorange/237be99b76f9477a1202789e377abd9c to your computer and use it in GitHub Desktop.
Save hisorange/237be99b76f9477a1202789e377abd9c to your computer and use it in GitHub Desktop.
ConverArrayToCsv.php
<?php
function ConvertArrayToCsv(
array $subject,
string $delimiter = ';',
string $enclosure = '"',
string $escape = '\\',
bool $pure = false
): string {
// Create a temporary resource.
$temp = tmpfile();
foreach ($subject as $nth => $row) {
// Check the first row for non numeric keys.
// If the it's not a sequence of numbers, then it will be used as header row.
if ($nth === 0 and ! empty(array_diff(array_keys($row), range(0, sizeof($row) - 1)))) {
fputcsv($temp, array_keys($row), $delimiter, $enclosure, $escape);
}
// Pure mode will remove the delimiter from the content, this is used to prevent
// parsing errors, where the parser ignores the enclosure character.
fputcsv($temp, $pure ? array_map(function ($value) use ($delimiter, $pure) {
return strtr($value, [$delimiter => ($pure === true ? '' : $pure)]); // Replace the delimiter in the value.
}, array_values($row)) : array_values($row), $delimiter, $enclosure, $escape);
}
// Reset the pointer.
rewind($temp);
// Get the content as string.
$csv = stream_get_contents($temp);
// Close the resource, this will remove the temporary resource.
fclose($temp);
return $csv;
}
// Source @hisorange.me
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment