Created
June 4, 2014 18:25
-
-
Save taichunmin/5cd6ad286e12da5a56e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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