Last active
August 29, 2015 14:23
-
-
Save polonskiy/47fc67e0bc7278570dd9 to your computer and use it in GitHub Desktop.
csv decode
This file contains hidden or 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 csv_decode($csv, $columns = [], $delimiter = ',', $enclosure = '"', $escape = '\\') { | |
$tmp = fopen('php://temp', 'rb+'); | |
fwrite($tmp, $csv); | |
rewind($tmp); | |
$result = []; | |
$assoc = (bool) $columns; | |
while (true) { | |
$record = fgetcsv($tmp, 0, $delimiter, $enclosure, $escape); | |
if ($record === null || $record === false) break; | |
if ($record === [null]) continue; //blank line | |
if ($assoc) { | |
foreach ($columns as $i => $name) { | |
$map[$name] = isset($record[$i]) ? $record[$i] : null; | |
} | |
$result[] = $map; | |
} else { | |
$result[] = $record; | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment