<?
class CSVParser {
const NL_WIN = "\r\n";
const NL_UNIX = "\n";
const NL_MAC = "\r";
public $filename;
public function setFilename($value) {
$this->filename = $value;
}
public $delimiter = ",";
public $quot = "\"";
public $lineBreakStyle;
public function __construct($filename = null, $lineBreakStyle = null) {
$this->filename = $filename;
$this->lineBreakStyle = !$lineBreakStyle ? self::NL_WIN : $lineBreakStyle;
}
public function parse($filename = null) {
$filename = $filename ? $filename : $this->filename;
if (!file_exists($filename)) return false;
$data = join("", file($filename));
### Flags
$quotOpened = false;
$newRow = true;
$word = "";
$row = null;
$list = array();
for ($i=0; $i<strlen($data); $i++) {
$sym = $data[$i]; #echo $sym;
$nextSym = @$data[$i+1];
### Quot
if ($sym == $this->quot && $nextSym != $this->quot) {
$quotOpened = !$quotOpened;
if (!$quotOpened) {
$row[] = $word;
$word = "";
}
continue;
}
### Escaped quot
if ($sym == $this->quot && $nextSym == $this->quot) {
$word .= $sym;
$i++;
continue;
}
### Delimiter
if ($sym == $this->delimiter && !$quotOpened) {
$row[] = $word;
$word = "";
continue;
}
### Row delimiter
if ($sym == @$this->lineBreakStyle[1] && !$quotOpened) {
### For WIN
if ($this->lineBreakStyle == self::NL_WIN) {
if ($word && $word != "\r") {
$row[] = $word;
}
}
$word = "";
$list[] = $row;
$row = null;
continue;
}
### Attach sym
$word .= $sym;
}
if ($this->lineBreakStyle == self::NL_WIN) {
if ($word && $word != "\r") {
$row[] = $word;
}
}
$list[] = $row;
return $list;
}
}
?>