Skip to content

Instantly share code, notes, and snippets.

@mgldev
Created February 16, 2015 13:58
Show Gist options
  • Save mgldev/fe098557f8e7e6b6e97a to your computer and use it in GitHub Desktop.
Save mgldev/fe098557f8e7e6b6e97a to your computer and use it in GitHub Desktop.
<?php
namespace App;
class CsvFile {
protected $closure;
protected $filename;
protected $skipHeadings = false;
public function __construct($filename, $skipHeadings = false, \Closure $closure = null) {
$this->filename = $filename;
$this->skipHeadings = $skipHeadings;
$this->closure = $closure;
}
public function getRows() {
$handle = @fopen($this->filename, 'r');
if (!$handle) {
throw new \RuntimeException('Unable to open "' . $this->filename . '"');
}
$csv = array();
$first = true;
while (($row = fgetcsv($handle, 1024, ",")) !== false) {
if ($first) {
$first = false;
if ($this->skipHeadings) {
continue;
}
}
if (!is_null($this->closure)) {
$row = call_user_func($this->closure, $row);
}
$csv[] = $row;
}
return $csv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment