The League of Extraordinary Packages

Our Packages:

Presented by The League of Extraordinary Packages

Getting Started

Connections

Inserting Records

Selecting Records

Converting Records

Upgrading Guide

This is the documentation for the upcoming version 9.0. This is a work in progress

Exceptions

Specific exceptions are thrown for errors occuring while using the library.

Default interface

All exceptions thrown implements the League\Csv\Exception\CsvException interface.

<?php

use League\Csv\Exception\CsvException;
use League\Csv\Reader;

try {
    $csv = Reader::createFromPath('/path/to/file.csv');
    $csv->setDelimiter('toto');
} catch (CsvException $e) {
    echo $e->getMessage(), PHP_EOL;
}

Logic exceptions

While setting properties

Setter methods will throw an InvalidArgumentException if the submitted value is invalid except for the createFromPath which can also triggers a RuntimeException if the filename cannot be opened like SplFileObject.

<?php

use League\Csv\Reader;

try {
    $csv = Reader::createFromPath('/path/to/file.csv'); //may trigger a RuntimeException
    $csv->setDelimiter('toto'); //may trigger a InvalidArgumentException
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), PHP_EOL;
} catch (RuntimeException $e) {
    echo $e->getMessage(), PHP_EOL;
}

// in PHP 7.1

try {
    $csv = Reader::createFromPath('/path/to/file.csv');
    $csv->setDelimiter('toto');
} catch (InvalidArgumentException | RuntimeException $e) {
    echo $e->getMessage(), PHP_EOL;
}

While using PHP stream support

If you try to use PHP stream filtering features on an CSV objects which can’t use them, a LogicException is triggered.

<?php

use League\Csv\Writer;

try {
    $csv = Writer::createFromFileObject(new SplTempFileObject());
    $csv->addStreamFilter('string.toupper');
} catch (LogicException $e) {
    echo $e->getMessage(), PHP_EOL;
}

Runtime exceptions

While manipulating records

During reading or writing records RuntimeException exception can be thrown if an error occurs.

<?php

use League\Csv\Reader;

try {
    $csv = Reader::createFromPath('/path/to/file.csv');
    $csv->setHeaderOffset(1000); //valid offset but the CSV does not contain 1000 records
    $header = $csv->getHeader(); //triggers a Exception
} catch (RuntimeException $e) {
    echo $e->getMessage(), PHP_EOL;
}

While inserting records

On error when using the Writer class to add new records to your CSV document a League\Csv\Exception\InsertionException is thrown. This exception class

<?php

use League\Csv\Writer;
use League\Csv\Exception\InsertionException;

try {
    $writer->insertOne(['john', ['doe'], 'john.doe@example.com']);
} catch (InsertionException $e) {
    echo $e->getName(); //display ''
    $e->getData();//will return the invalid data ['john', ['doe'], 'john.doe@example.com']
}