Created
April 27, 2012 01:57
-
-
Save eddieajau/2505017 to your computer and use it in GitHub Desktop.
A class method that can be used to import a CSV file of any size using SplFileObject.
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
/** | |
* Import a CSV file. | |
* | |
* @param string $fileName The name of the file to import. If omitted, the state is used. | |
* @param integer $offset The number of lines/rows to ignore (default = 0). | |
* | |
* @return void | |
* | |
* @since 1.0 | |
* @throws InvalidArgumentException if file name is invalid or does not exist. | |
*/ | |
public function import($fileName = null, $offset = 0) | |
{ | |
if (empty($fileName) || !is_file($fileName)) | |
{ | |
throw new InvalidArgumentException(sprintf('%s(%s).', __METHOD__, $fileName)); | |
} | |
$file = new SplFileObject($fileName); | |
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY); | |
// Adjust delimiters, etc, as required. | |
//$file->setCsvControl(';'); | |
foreach (new LimitIterator($file, $offset) as $row) | |
{ | |
// Work on the row. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment