Skip to content

Instantly share code, notes, and snippets.

@objectoriented
Created March 18, 2016 15:15
Show Gist options
  • Save objectoriented/4692e176094b72ba65f8 to your computer and use it in GitHub Desktop.
Save objectoriented/4692e176094b72ba65f8 to your computer and use it in GitHub Desktop.
<?php
class Csv implements Iterator {
private $_file = null;
private $_rows = 0;
private $_header = array();
private $_emptyRow = array();
private $_delimiter = '\t';
private $_idFieldName = null;
private $_record = array();
function __construct($url, $delimiter = '\t', $uniqueIdField = null) {
$this->_file = fopen($url, "r");
$this->_delimiter = $delimiter;
$this->_idFieldName = $uniqueIdField;
if (!$this->_file) throw new Exception('Failed to open URL: ' . $url);
}
function __destruct() {
fclose($this->_file);
}
public function next() {
$this->_record = $this->consumeNextRecord();
}
public function current() {
return $this->_record;
}
public function valid() {
return !feof($this->_file);
}
public function rewind() {
rewind($this->_file);
$this->consumeHeaderRow(); // skip the header row
$this->next(); // advance to the first record
}
public function key() {
return $this->_record[$this->_idFieldName];
}
///
public function consumeHeaderRow() {
$this->_header = fgetcsv($this->_file, 0, $this->_delimiter);
$header_count = count($this->_header);
$this->_emptyRow = array_fill(0, $header_count, null);
}
public function consumeNextRecord() {
if (($data = fgetcsv($this->_file, 0, $this->_delimiter)) === false) {
return false;
}
$this->_rows++;
$row = array_replace($this->_emptyRow, $data); // php 5.3 feature
$record = array_combine($this->_header, $row);
return $record;
}
public function getRecordNumber() {
return $this->_rows;
}
}
///
/// command line usage:
/// php simple_csv_reader.php [csv file path] [delimiter] [name of the product ID field]
/// php simple_csv_reader.php my_file.csv "," "product_id"
///
$url = $argv[1];
$delimiter = $argv[2];
$idFieldName = $argv[3];
$esUrl = $argv[4];
////
$csv = new Csv($url, $delimiter, $idFieldName);
foreach ($csv as $id => $rec) {
print_r($rec);
}
echo "Total Rows: " . $csv->getRecordNumber() . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment