Skip to content

Instantly share code, notes, and snippets.

@polonskiy
Last active August 29, 2015 14:23
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 polonskiy/47fc67e0bc7278570dd9 to your computer and use it in GitHub Desktop.
Save polonskiy/47fc67e0bc7278570dd9 to your computer and use it in GitHub Desktop.
csv decode
<?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