Skip to content

Instantly share code, notes, and snippets.

@taichunmin
Created June 4, 2014 18:25
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 taichunmin/5cd6ad286e12da5a56e4 to your computer and use it in GitHub Desktop.
Save taichunmin/5cd6ad286e12da5a56e4 to your computer and use it in GitHub Desktop.
<?php
/**
* 用於讀取 TAB 分隔之資料 (就是直接從 Excel 複製出來的資料格式)
*/
class tsvResult_C
{
private $header, $fin, $rowCache = array();
function __construct($filename)
{
if( ! $this->_fopen( $filename ) )
throw new Exception('tsvResult_C error');
$this->header = $this->_getRow();
}
function __destruct()
{
@fclose($this->fin);
unset($this->header);
unset($this->fin);
}
private function _fopen( $filename )
{
$this->num_rows = 0;
$this->fin = fopen($filename, 'r');
return (bool)$this->fin;
}
private function _getRow()
{
if( count($this->rowCache) )
return array_shift($this->rowCache); // Return from Cache
$line = $this->_getline();
if( $line === false )
return null;
$tmp = explode("\t", $line);
if( count($this->header)>0 && count($this->header) != count($tmp) )
{
while( count($this->header) > count($tmp) )
{
$tmp2 = explode("\t", $this->_getline());
$tmp[count($tmp)-1] .= PHP_EOL . array_shift($tmp2);
if(count($tmp2))
$tmp = array_merge($tmp, $tmp2);
}
if( count($this->header) < count($tmp) )
throw new Exception('Column count not match :' . $line );
}
return $tmp;
}
private function _getline()
{
return stream_get_line($this->fin, 1000000, "\r\n");
}
public function fetch_assoc()
{
if( $tmp = $this->_getRow() )
return array_combine($this->header, $tmp);
else return null;
}
public function fetch_row()
{
if( $tmp = $this->_getRow() )
return $tmp;
else return null;
}
public function header()
{
return $this->header;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment