LeagueCSV

Versions

Overview

Connection type

Accessing the CSV document is done using one of the following classes:

Both classes extend the League\Csv\AbstractCsv class and as such share the following features:

OS specificity

If your CSV document was created or is read on a Legacy Macintosh computer, add the following lines before using the library to help PHP detect line ending.

if (!ini_get('auto_detect_line_endings')) {
    ini_set('auto_detect_line_endings', '1');
}

auto_detect_line_endings is deprecated since PHP 8.1; and will be removed in PHP 9.0

Exceptions

The default exception class thrown while using this library is League\Csv\Exception which extends PHP Exception class.

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

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

When using a non-seekable SplFileObject, a RuntimeException is thrown instead of a League\Csv\Exception when using features that require a seekable CSV document. In the following example a seekable CSV document is required to update the inserted end of line sequence.

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

try {
    $csv = Writer::createFromFileObject(new SplFileObject('php://output', 'w'));
    $csv->setEndOfLine("\r\n");
    $csv->insertOne(["foo", "bar"]);
} catch (Exception | RuntimeException $e) {
    echo $e->getMessage(), PHP_EOL;
}

//in order to change the CSV document end of line a seekable CSV document is required