Created
May 29, 2018 20:35
-
-
Save hisorange/237be99b76f9477a1202789e377abd9c to your computer and use it in GitHub Desktop.
ConverArrayToCsv.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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