delimiter = $delim; } if($enclosure) { $this->enclosure = $enclosure; } if($escape) { $this->escape = $escape; } } public function setTemplate(array $tpl_array) { $this->template = $tpl_array; return $this; } public function setFirstLineIsHeading($bool) { $this->first_line_is_heading = (bool)$bool; return $this; } public function parseFile($filename) { $ret = array(); if($handle = fopen($filename, 'r')) { $first_line = $this->first_line_is_heading; while(($data = $this->nextCSVLine($handle)) !== false) { if($first_line) { $first_line = false; // Save template $this->setTemplate($data); }else{ // Save values using key names $i = 0; $line = array(); foreach($data as $value) { // Save with numeric index $line[$i] = $value; // Save with template name if(isset($this->template[$i])) { $line[$this->template[$i]] = $value; } $i++; } $ret[] = $line; } } fclose($handle); } return $ret; } /*--- Private Implementation ---*/ /** * Returns next line for a filehandle as a array. * * @param filehandle Filehandle to use. * @return array of CSV Line or false. */ protected function nextCSVLine($filehandle) { return fgetcsv($filehandle, 4096, $this->delimiter, $this->enclosure, $this->escape); } } /* // Some example code: $csv = new CSV(); $csv->setFirstLineIsHeading(true); //$csv->setFirstLineIsHeading(false); $tpl = range('a', 'z'); $csv->setTemplate($tpl); $data = $csv->parseFile('test.csv'); var_dump($data); */