League CSV Documentation

website·Indexed 37 days ago

https://csv.thephpleague.com/9.0/

Documentation for the League CSV PHP library, covering CSV reading, writing, and record conversion. Includes guides for version 9.0, as well as legacy documentation for versions 7.0 and 8.0, with details on stream filtering, BOM character management, and JSON/XML conversion.

Tokens
53K
Snippets
330
Records
388
Agent score
65%

What's inside League CSV

  1. Overview of the Tabular Data Buffer

    The League\Csv\Buffer class (available since version 9.22.0) provides an in-memory unit for managing and transforming tabular data using CRUD operations. Because it stores all data in-memory, it does not use PHP stream capabilities and is not suitable for very large datasets; developers must manually limit the buffer size to avoid memory exhaustion.
  2. Overview of League\CSV extensions

    League\CSV provides a set of independent extension packages designed to add advanced functionality to the core library. These are maintained as standalone packages to ensure the core package remains slim and to avoid forcing users to install dependencies that are only required for specific extended features.
  3. Overview of League Csv v7.0

    League Csv is a lightweight PHP library designed to simplify CSV parsing, writing, and filtering by utilizing native PHP classes. Note: Version 7.0 is unsupported; users are encouraged to upgrade to the latest stable version.

  4. Overview of the TabularDataReader interface

    Introduced in version 9.6, the League Csv TabularDataReader interface provides a common API for working with tabular data structures such as CSV documents, HTML tables, and RDBMS tables.

    Key characteristics:

    • Immutability: Most methods return a new TabularDataReader instance, leaving the source data unchanged.
    • Structure: Tabular data consists of a collection of similar records (non-nested PHP arrays) and an optional header containing unique string values.
    • Capabilities: Supports filtering, slicing, and selecting data, and can be processed using a Statement object.
    use League
    Csv
    Reader;
    
    $records = Reader::from('/path/to/file.csv')
        ->filter(fn (array $record): bool => false !== filter_var($record[2] ?? '', FILTER_VALIDATE_EMAIL))
        ->select(1, 4, 5)
        ->slice(3, 5)
        ->each(function (array $record) {
            // Process records
        });
  5. Overview of League\Csv\ResultSet

    The League\Csv\ResultSet object represents the result set produced when processing a CSV document using a constraint builder (Statement). It is typically returned by the Statement::process() method. As of version 9.6.0, it implements League\Csv TabularDataReader, and as of version 9.22.0, it implements League\Csv\TabularData.
  6. Choose between Reader and Writer for CSV access

    The League Csv library provides two primary classes for accessing CSV documents, both of which extend League Csv AbstractCsv. Use League Csv Reader for read-only access and League Csv Writer for write-only access. Both classes support loading documents, configuring control characters, managing BOM sequences, adding PHP stream filters, and outputting the document.

  7. Filter and sort CSV data using query options

    Query options allow you to restrict the output of extract methods (like fetchAssoc) and conversion methods (like toHTML, toXML, jsonSerialize).

    Key behaviors:

    • Methods are chainable (unless they return a boolean).
    • Options can be called in any order before an extract/conversion method.
    • All query options are cleared immediately after an extract/conversion method is called.
    • The order of application is: Filtering $\rightarrow$ Sorting $\rightarrow$ Interval (Offset/Limit) $\rightarrow$ Extraction.
    • Filtering and Sorting follow the First In First Out (FIFO) rule.
  8. Convert CSV records to XML, HTML, or JSON

    The league/csv package provides specialized converter classes to transform collections of CSV records into different formats. Available converters include:

    • XMLConverter: Converts records into a DOMDocument object.
    • HTMLConverter: Converts records into an HTML table.
    • JsonConverter: Converts records into a JSON document.

    Note: A League oresaid\Csv\Writer object cannot be converted; converters operate on collections of records.

  9. Prevent CSV Formula Injection using EscapeFormula

    The EscapeFormula formatter (available since version 9.1.0) reduces CSV Formula Injection risks in spreadsheet programs by prepending a specific escape character to fields that start with dangerous characters. By default, it escapes fields starting with +, -, =, @, \t, or \r. This implementation follows OWASP recommendations for CSV injection prevention.
  10. Extract CSV data using League\Csv\Reader

    To extract data from a CSV document, use the methods provided by League\Csv\Reader. When using Reader::createFromPath, the default mode is r+ (which checks for write permissions). It is strongly recommended to explicitly set the mode to r to ensure the file can be opened without permission exceptions.
  11. Understand League Csv document interoperability behavior

    By default, League\Csv connections do not alter the presentation of the CSV document. The library relies on PHP's native CSV functions to read and write records. Depending on the operating system or software used to import the CSV, developers may need to manually address specific interoperability issues such as encoding/BOM presence, RFC4180 field compliance, adding enclosure characters to all fields, or preventing CSV formula injection.
  12. Export a database table to a CSV document

    Use the Writer class to create a CSV document from a PDOStatement. By using Writer::from(new SplTempFileObject()), the CSV is created in memory. The insertAll() method can be used to insert all records from a Traversable object (like a PDOStatement), and output() can be used to trigger a browser download with the specified filename.
    use League\Csv\Writer;
    
    // Fetch data using a PDO object
    $sth = $dbh->prepare(
        "SELECT firstname, lastname, email FROM users LIMIT 200"
    );
    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $sth->execute();
    
    // Create the CSV into memory
    $csv = Writer::from(new SplTempFileObject());
    $csv->setEscape(''); // required in PHP8.4+ to avoid deprecation notices
    
    // Insert the CSV header
    $csv->insertOne(['firstname', 'lastname', 'email']);
    
    // Insert the PDOStatement data
    $csv->insertAll($sth);
    
    // Trigger browser download
    $csv->output('users.csv');
    die;