Skip to content

Instantly share code, notes, and snippets.

@tsmsogn
Last active August 29, 2015 14:00
Show Gist options
  • Save tsmsogn/11277725 to your computer and use it in GitHub Desktop.
Save tsmsogn/11277725 to your computer and use it in GitHub Desktop.
[cakephp]CSV Import Helper
<?php
/**
* CsvImport Helper
*
* @author Toshimasa Oguni <tsmsogn@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class CsvImportHelper {
private $__default = array('delimiter' => ',', 'enclosure' => '"', 'hasHeader' => true, 'headerMap' => '');
public function __construct($settings = array()) {
if (!is_array($settings)) {
$settings = array();
}
$this->__default = array_merge($this->__default, $settings);
}
/**
* Returns a line form the CSV file and advances the pointer to the next one
*
* @param SplFileObject $handle CSV file handler
* @return array list of attributes fetched from the CSV file
*/
protected function _getCSVLine(SplFileObject $handle) {
if ($handle->eof()) {
return false;
}
return $handle->fgetcsv(
$this->__default['delimiter'],
$this->__default['enclosure']
);
}
/**
* Returns a list of keys representing the columns of the CSV file
*
* @param SplFileObject $handle CSV file handler
* @return array list of attributes fetched from the CSV file
*/
protected function _getHeader(SplFileObject $handle) {
if ($this->__default['hasHeader'] === true) {
if ($this->__default['headerMap']) {
return call_user_func($this->__default['headerMap'], $this->_getCSVLine($handle));
} else {
return $header = $this->_getCSVLine($handle);
}
}
}
/**
* Returns a list of keys representing the columns of the CSV file
*
* @param string $file path to the CSV file
* @throws RuntimeException if $file does not exists
* @return array list of data from the CSV
*/
public function importCSV($file) {
$this->convert_encodings($file);
$handle = new SplFileObject($file, 'rb');
//$handle->setFlags(SplFileObject::SKIP_EMPTY);
$header = $this->_getHeader($handle);
$data = array();
while ($row = $this->_getCSVLine($handle)) {
if (!empty($header)) {
$tmp = array();
foreach ($header as $k => $col) {
// get the data field from Model.field
if (strpos($col, '.') !== false) {
$keys = explode('.', $col);
if (isset($keys[2])) {
$tmp[$keys[0]][$keys[1]][$keys[2]] = (isset($row[$k])) ? $row[$k] : '';
} else {
$tmp[$keys[0]][$keys[1]] = (isset($row[$k])) ? $row[$k] : '';
}
} else {
$tmp[$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$data[] = $tmp;
} else {
$data[] = $row;
}
}
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment