Skip to content

Instantly share code, notes, and snippets.

@eddieajau
Created April 27, 2012 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eddieajau/2505017 to your computer and use it in GitHub Desktop.
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.
/**
* 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