Skip to content

Instantly share code, notes, and snippets.

@akkunchoi
Created June 14, 2013 01:54
Show Gist options
  • Select an option

  • Save akkunchoi/5778894 to your computer and use it in GitHub Desktop.

Select an option

Save akkunchoi/5778894 to your computer and use it in GitHub Desktop.
<?php
$options = array('colDelimiter' => ',');
csv('./test.csv', $options, function($row){
var_dump($row);
});
function csv($fp, $options = array(), $callback = null){
if (is_string($fp)){
$fp = fopen($fp, 'r');
}
if (is_callable($options) && is_null($callback)){
$callback = $options;
$options = array();
}
$count = 0;
$header = null;
$colDelimiter = ',';
$seek = 1000;
extract($options);
while (($data = fgetcsv($fp, $seek, $colDelimiter)) !== FALSE) {
$data = array_map('trim', $data);
if (is_null($header)){
$header = $data;
continue;
}
$assoc = array();
foreach ($header as $i => $value){
if (isset($data[$i])){
$assoc[$value] = $data[$i];
}else{
$assoc[$value] = '';
}
}
if ($callback && is_callable($callback)){
$callback($assoc);
}
}
fclose($fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment