Friday, April 25, 2008

class CsvIterator implements Iterator

Looks like a useful class for handling CSV files.
I haven't tested it yet.






filePointer = fopen($file, 'r');

$this->delimiter = $delimiter;

}

catch (Exception $e) {

throw new Exception('The file "'.$file.'" cannot be read.');

}

}

/**

* This method resets the file pointer.

*

* @access public

*/

public function rewind() {

$this->rowCounter = 0;

rewind($this->filePointer);

}

/**

* This method returns the current csv row as a 2 dimensional array

*

* @access public

* @return array The current csv row as a 2 dimensional array

*/

public function current() {

$this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);

$this->rowCounter++;

return $this->currentElement;

}

/**

* This method returns the current row number.

*

* @access public

* @return int The current row number

*/

public function key() {

return $this->rowCounter;

}

/**

* This method checks if the end of file is reached.

*

* @access public

* @return boolean Returns true on EOF reached, false otherwise.

*/

public function next() {

return !feof($this->filePointer);

}

/**

* This method checks if the next row is a valid row.

*

* @access public

* @return boolean If the next row is a valid row.

*/

public function valid() {

if (!$this->next()) {

fclose($this->filePointer);

return false;

}

return true;

}

}

?>

Usage :

$data) {

// do somthing with $data

}

?>

Labels:


0 Comments:

Post a Comment

<< Home