CsvIterator – csv/tsv import class

About the CsvIterator class

The class CvsIterator.class.php imports and reads csv files – but also other files that have a similar format with a defined separator / delimiter as e.g. a semicolon ; or a tab t or a comma , . Also, enclosures as e.g. quotation marks ” are supported.

Features of CsvIterator class

  • Reads csv, tsv files
  • Supports headers, returns the rows as named arrays with the appropriate header column name as key
  • Iterator – like functionality
  • Can be used to read other/custom formats with different delimiters as e.g. pipe | easily
  • It even supports enclosures as e.g. quotation marks “
  • Copy – include – run – usage
  • Requires at least PHP 4.3, no special library necessary

Download the csv / tsv php import class

CsvImport Release 1.1
License: GPL

How to read and import a csv file

include('CsvIterator.class.php');
$csvIterator = new CsvIterator('/path/to/file', true);
while ($csvIterator->next()) {
print_r($csvIterator->current());
}

This code example opens a file in csv format, located at /path/to/file, that contains a first row with a header / description of the csv rows.

How to read and import a tsv file

include('CsvIterator.class.php');
$csvIterator = new CsvIterator('/path/to/file', true, "t");
while ($csvIterator->next()) {
print_r($csvIterator->current());
}

This code example opens a file in tsv (tab-separated values) format, located at /path/to/file, that contains a first row with a header / description of the csv rows. The separator / delimiter is – of course – a tab, encoded as t.

How to read and import a custom format

Assuming that your files have the following format: the entries are separated by a pipe |, each entry is enclosed with quotation marks “” as the first and last character.
A example row would look like "value1"|"value2 that can even contain a pipe | or other characters".
The import code would be the following:
$csvIterator = new CsvIterator('/path/to/file', true, '|', '"');
while ($csvIterator->next()) {
print_r($csvIterator->current());
}

That’s it!

Please leave a comment or link to this page if you like it!