Skip to content

Instantly share code, notes, and snippets.

@barryvdh
Last active August 19, 2021 11:55
Show Gist options
  • Save barryvdh/2aa4a577a035309c5286a3b9b39421fd to your computer and use it in GitHub Desktop.
Save barryvdh/2aa4a577a035309c5286a3b9b39421fd to your computer and use it in GitHub Desktop.
<?php
class Csv
{
public static function fromArray($rows, $delimiter = ',')
{
if (empty($rows)) {
return '';
}
// Limit CSV to 32 MB in memory
$handle = fopen('php://temp/maxmemory:'. (32*1024*1024), 'r+');
// Write Byte Order Mark for UTF-8
fputs($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));
$headers = array_keys(array_values($rows)[0]);
fputcsv($handle, $headers, $delimiter);
foreach ($rows as $row) {
fputcsv($handle, array_values($row), $delimiter);
}
rewind($handle);
return stream_get_contents($handle);
}
public static function toArray($csvString, $delimiter = ',')
{
if (is_resource($csvString)) {
$handle = $csvString;
} else {
$handle = fopen('php://memory','r+');
fwrite($handle, (string) $csvString);
rewind($handle);
}
$rows = [];
while ($row = fgetcsv($handle, 0, $delimiter)) {
$rows[] = array_map(function($value) {
return static::convertEncoding($value);
}, $row);
}
$headers = array_shift($rows);
$headers = array_map('trim', $headers);
$data = array_map(function($row) use($headers) {
return array_combine($headers, $row);
}, $rows);
return $data;
}
public static function convertEncoding($input)
{
return iconv(mb_detect_encoding($input, mb_detect_order(), true), 'UTF-8//IGNORE', $input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment