-
-
Save softquantum/c0fd42298e7f820079d9f737e6abbdf8 to your computer and use it in GitHub Desktop.
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 | |
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 = ',') | |
{ | |
$lines = explode("\n", $csvString); | |
$rows = []; | |
foreach ($lines as $line) { | |
$line = self::convertEncoding($line); | |
if (!empty($line)) { | |
$rows[] = str_getcsv($line, $delimiter); | |
} | |
} | |
$headers = array_shift($rows); | |
$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