### Install league/csv Package Source: https://github.com/thephpleague/csv/blob/master/README.md Install the league/csv package using Composer. This command ensures you get version 9.0 or higher. ```bash composer require league/csv:^9.0 ``` -------------------------------- ### Install League\Csv with Composer Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/installation.md Use Composer to install the league/csv package, specifying version 8.0 or higher. ```bash composer require league/csv:^8.0 ``` -------------------------------- ### Install League Csv using Composer Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/installation.md Use this command to install the latest stable version of the League\Csv package via Composer. ```bash composer require league/csv:^{{ site.data.project.version }} ``` -------------------------------- ### Install League Csv with Composer Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/installation.md Use Composer to install the League Csv library version 7.0 or higher. This is the recommended installation method. ```bash composer require league/csv:^7.0 ``` -------------------------------- ### Example String Values for Different Array Shapes Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/record-mapping.md Demonstrates the expected string format for 'list', 'csv', and 'json' array shapes. ```php $array['list'] = "1,2,3,4"; //the string contains only a delimiter (shape list) $array['csv'] = '"1","2","3","4"'; //the string contains delimiter and enclosure (shape csv) $array['json'] = '{"foo":"bar"}'; //the string is a json string (shape json) ``` -------------------------------- ### Counting and Iterating CSV Records Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/tabular-data-reader.md This example shows how to get the total number of records in a CSV file and how to iterate over each record using a foreach loop. The Reader instance implements Countable and IteratorAggregate interfaces. ```php use League\Csv\Reader; $reader = Reader::from('/path/to/my/file.csv'); count($reader); //returns 4 foreach ($reader as $offset => $record) { //iterates over the 4 records. } ``` -------------------------------- ### Install League Csv 7.0 Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/upgrading.md Update your composer.json file to require version 7.0 of League Csv. ```bash composer require league/csv:~7.0 ``` -------------------------------- ### Defining a Record Formatter Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/buffer.md Illustrates how to define and use a record formatter callable. This example converts all values in a record to uppercase before insertion into the buffer. ```php function(array $record): array { return array_map('strtoupper', $row); } ``` ```php $buffer = new Buffer(); $buffer->addFormatter(fn (array $row): array => array_map('strtoupper', $row)); $buffer->insert(['john', 'doe', 'john.doe@example.com']); $buffer->last(); //returns ['JOHN', 'DOE', 'JOHN.DOE@EXAMPLE.COM'] ``` -------------------------------- ### Adding a Record Formatter Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/index.md Example of adding a formatter to convert all record values to uppercase. Formatters are applied in FIFO order. ```php use League\ Csv\Writer; $formatter = function (array $row): array { return array_map('strtoupper', $row); }; $writer = Writer::from(new SplTempFileObject()); $writer->addFormatter($formatter); $writer->insertOne(['john', 'doe', 'john.doe@example.com']); echo $writer->toString(); //will display JOHN,DOE,JOHN.DOE@EXAMPLE.COM ``` -------------------------------- ### Enclosing All Records Example Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/index.md Demonstrates how to force enclosure around all record entries. This setting ignores the escape character. ```php encloseAll(); //return false; $writer->forceEnclosure(); $writer->encloseAll(); //return true; $writer->insertAll($collection); echo $writer->toString(), PHP_EOL; // the CSV file will contain enclosed cell. // Double quote are not added in presence of the // escape character as per PHP's CSV writing documentation // "1","2" // "value 2-0","value 2-1" // "to""to","foo\"bar" ``` -------------------------------- ### Transcoding Charset - Old vs New Source: https://github.com/thephpleague/csv/blob/master/docs/upgrading/6.0.md Illustrates the change in method names for setting and getting the input encoding. `setEncoding` is now `setEncodingFrom` and `getEncoding` is now `getEncodingFrom`. ```php use League\Csv\Reader; $reader = new Reader('/path/to/your/csv/file.csv'); $reader->setEncoding('SJIS'); $charset = $reader->getEncoding(); //returns 'SJIS' $reader->output(); ``` ```php use League\Csv\Reader; $reader = new Reader('/path/to/your/csv/file.csv'); $reader->setEncodingFrom('SJIS'); $charset = $reader->getEncodingFrom(); //returns 'SJIS' $reader->output(); ``` -------------------------------- ### Deprecated AfterMapping Attribute Example Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/record-mapping.md Reference for the deprecated `AfterMapping` attribute, which is ignored if `MapRecord` is also used. ```php use League\Csv\Serializer; #[Serializer\AfterMapping('validate')] final class ClimateRecord { public function __construct( public readonly Place $place, public readonly ?float $temperature, public readonly ?DateTimeImmutable $date, ) { $this->validate(); } protected function validate(): void { //further validation on your object //or any other post construction methods //that is needed to be called } } ``` -------------------------------- ### Setting and Getting Output BOM Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/bom.md Use `setOutputBOM` to specify the BOM sequence for the CSV output and `getOutputBOM` to retrieve the currently set BOM. The default output BOM is an empty string. ```php public AbstractCsv::setOutputBOM(Bom|string|null $sequence): self public AbstractCsv::getOutputBOM(void): string ``` ```php use League\Csv\Bom; use League\Csv\Reader; $csv = Reader::from('/path/to/file.csv', 'r'); $csv->setOutputBOM(Bom::Utf8); $bom = $csv->getOutputBOM(); //returns "\xEF\xBB\xBF" ``` -------------------------------- ### Retrieving First and Last Records Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/buffer.md Shows how to get the first and last records from a Buffer, either as an array or mapped to a specified object. Handles cases where the buffer is empty. ```php $buffer->first(); //returns ['firstname' => 'john', 'lastname' => 'doe', 'email' => 'johh.doe@example.com'] $buffer->firstAsObject(User::class); // returns a User instance on success $emptyBuffer->last(); // returns [] $emptyBuffer->lastAsObject(User::class); // returns null ``` -------------------------------- ### Validation Example Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/inserting.md Demonstrates how to add a custom validator to check if a row contains exactly 10 cells and how to catch and handle `InvalidRowException`. ```APIDOC ## Validation Example ### Description This example shows how to implement and use a custom row validator and handle potential validation errors. ### Code ```php use League\Csv\Writer; use League\Csv\Exception\InvalidRowException; // Assuming $writer is an instance of League\Csv\Writer // Add a validator that checks if the row has exactly 10 cells $writer->addValidator(function (array $row) { return 10 == count($row); }, 'row_must_contain_10_cells'); try { // Attempt to insert a row with fewer than 10 cells $writer->insertOne(['john', 'doe', 'john.doe@example.com']); } catch (InvalidRowException $e) { // Handle the validation failure echo "Validation failed: " . $e->getName(); // Output: Validation failed: row_must_contain_10_cells echo "\nInvalid data: "; print_r($e->getData()); // Output: Array ( [0] => john [1] => doe [2] => john.doe@example.com ) } ``` ``` -------------------------------- ### Catch League Csv Exceptions Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/index.md Demonstrates how to catch `League\Csv\Exception` when performing CSV operations, such as setting an invalid delimiter. This example shows basic exception handling. ```php use League\Csv\Exception; use League\Csv\Reader; try { $csv = Reader::from('/path/to/file.csv', 'r'); $csv->setDelimiter('toto'); } catch (Exception $e) { echo $e->getMessage(), PHP_EOL; } ``` -------------------------------- ### Downloading CSV as JSON with General Headers Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/converter/json.md Saves CSV data as a JSON file and sends it to the browser for download. This example includes common caching and content type headers required for file downloads. ```php use League\Csv\Reader; use League\Csv\JsonConverter; $reader = Reader::from('file.csv'); $reader->setHeaderOffset(0); header('Cache-Control: no-cache, no-store, must-revalidate'); header('Pragma: no-cache'); header('Expires: 0'); header('Content-Type: application/json; charset=UTF-8'); header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename="name-for-your-file.json"'); (new JsonConverter())->download($reader); die; ``` -------------------------------- ### Set and Get Output BOM Sequence Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/properties.md The `setOutputBOM` method sets the desired BOM for the CSV output, while `getOutputBOM` retrieves the currently set BOM. Note that `getOutputBOM` always returns a string. ```php use League\Csv\Reader; $csv = Reader::createFromPath('/path/to/file.csv', 'r'); $csv->setOutputBOM(Reader::BOM_UTF8); $bom = $csv->getOutputBOM(); //returns "\xEF\xBB\xBF" ``` -------------------------------- ### Detecting Delimiter Stats with League Csv Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/controls.md This example demonstrates how to use `Info::getDelimiterStats` to find the delimiter character in a CSV file. It configures a Reader and then calls the static method with potential delimiters and a record limit. ```php use League\Csv\Info; use League\Csv\Reader; $reader = Reader::from('/path/to/file.csv', 'r'); $reader->setEnclosure('"'); $reader->setEscape('\\'); $result = Info::getDelimiterStats($reader, [' ', '|'], 10); // $result can be the following // [ // '|' => 20, // ' ' => 0, // ] // This seems to be a consistent CSV with: // - 20 fields were counted with the "|" delimiter in the 10 first records; // - in contrast no field was detected for the " " delimiter; ``` -------------------------------- ### Including Input BOM and Setting Output BOM Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/bom.md Example demonstrating how to include the input BOM and set a different output BOM. This can result in multiple BOM markers in the final output if both input and output BOMs are present and configured. ```php $raw_csv = Bom::Utf8->value."john,doe,john.doe@example.com\njane,doe,jane.doe@example.com\n"; $csv = Reader::fromString($raw_csv); $csv->setOutputBOM(Bom::Utf16Le); $csv->includeInputBOM(); ob_start(); $csv->output(); $document = ob_get_clean(); ``` -------------------------------- ### Buffer State and Information Methods Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/buffer.md Demonstrates how to check the state of a Buffer instance, including whether it has a header, is empty, and retrieves offset and record count information. Also shows the behavior of an empty buffer. ```php use League\Csv\Buffer; use League\Csv\Reader; use League\Csv\Statement; $reader = Reader::from('/path/to/file.csv'); $reader->setHeaderOffset(0); $buffer = Buffer::from($reader->slice(50, 30000))); $buffer->isEmpty(); // returns false $buffer->hasHeader(); // returns true $buffer->firstOffset(); // returns 50 $buffer->lastOffset(); // returns the offset of the last inserted record $buffer->recordCount(); // the total number of rows in the instance $emptyBuffer = new Buffer(); $emptyBuffer->isEmpty(); // returns true $emptyBuffer->hasHeader(); // returns false $emptyBuffer->firstOffset(); // returns null $emptyBuffer->lastOffset(); // returns null $emptyBuffer->recordCount(); // returns 0 ``` -------------------------------- ### Set and Get SplFileObject Flags Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/properties.md Adjust internal SplFileObject flags to fine-tune CSV reading behavior. Examples include READ_AHEAD and SKIP_EMPTY. ```php $csv->setFlags(SplFileObject::READ_AHEAD|SplFileObject::SKIP_EMPTY); $flags = $csv->getFlags(); //returns an integer ``` -------------------------------- ### Creating New Instances - Old vs New Source: https://github.com/thephpleague/csv/blob/master/docs/upgrading/6.0.md Shows the removal of `getReader`/`getWriter` and the introduction of `newReader`/`newWriter` on both Reader and Writer objects for creating new instances. ```php use League\Csv\Reader; $reader = new Reader('/path/to/your/csv/file.csv'); $writer = $reader->getWriter('a+'); $another_reader = $writer->getReader(); ``` ```php use League\Csv\Reader; $reader = Reader::createFromPath('/path/to/your/csv/file.csv', 'r'); $writer = $reader->newWriter('a+'); $another_writer = $writer->newWriter('rb+'); $another_reader1 = $writer->newReader(); $another_reader2 = $reader->newReader(); ``` -------------------------------- ### Updating Records Based on a Column Filter Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/buffer.md Shows how to update records in a buffer where a specific column matches a given value. This example uses a `Column` predicate to filter by 'location' and updates matching records to 'Galway'. ```php use League\Csv\Buffer; use League\Csv\Query\Constraint\Column; use League\Csv\Reader; $reader = Reader::from('path/to/file.csv'); $reader->setHeaderOffset(0); $buffer = Buffer::from($reader->slice(0, 300)); //copy the first 300 lines of the Reader class $affectedRowsCount = $buffer->update( Column::filterOn('location', '=', 'Berkeley'), ['location' => 'Galway'] ); ``` -------------------------------- ### Filter and Sort CSV Data for fetchAssoc Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/query-filtering.md Use addFilter and addSortBy to modify the output of fetchAssoc. This example restricts results to valid emails and sorts by last name, starting from a specific offset and limit. ```php function filterByEmail($row) { return filter_var($row[2], FILTER_VALIDATE_EMAIL); } function sortByLastName($rowA, $rowB) { return strcmp($rowB[1], $rowA[1]); } $data = $reader ->stripBom(false) ->setOffset(3) ->setLimit(2) ->addFilter('filterByEmail') ->addSortBy('sortByLastName') ->fetchAssoc(['firstname', 'lastname', 'email'], function ($value) { return array_map('strtoupper', $value); }); // data length will be equals or lesser that 2 starting from the row index 3. // will return something like this : // // [ // ['firstname' => 'JANE', 'lastname' => 'RAMANOV', 'email' => 'JANE.RAMANOV@EXAMPLE.COM'], // ['firstname' => 'JOHN', 'lastname' => 'DOE', 'email' => 'JOHN.DOE@EXAMPLE.COM'], // ] ``` -------------------------------- ### Filtering Records with Comparison Operators Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/statement.md Utilize `andWhere`, `orWhere`, and `whereNot` for filtering based on column values using operators. This example filters for records where the second column is '10', or the 'birthdate' column matches a regex, and the 'firstname' does not start with 'P'. ```php use League\Csv\Reader; use League\Csv\Statement; $reader = Reader::from('/path/to/file.csv'); $records = (new Statement()) ->andWhere(1, '=', '10') //filtering is done of the second column ->orWhere('birthdate', 'regexp', '/\d{1,2}\/\d{1,2}\/\d{2,4}/') //filtering is done on the `birthdate` column ->whereNot('firstname', 'starts_with', 'P') //filtering is done case-sensitively on the first character of the column value ->process($reader); // $records is a League\Csv\ResultSet instance ``` -------------------------------- ### Creating a Buffer with Header from Reader Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/buffer.md Illustrates how to create a Buffer instance with a header by loading data from a League Csv Reader that has its header offset defined. ```php $document = Reader::from('path/to/file.csv'); $document->setHeaderOffset(0); //the Reader header will be imported alongside its records $buffer = Buffer::from($document); $buffer->getHeader(); // returns ['column1', 'column2', 'column3'] $buffer->hasHeader(); // return true ``` -------------------------------- ### Set and Get Delimiter Character Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/properties.md Configure the delimiter character for CSV parsing and retrieval. The default is ','. ```php $csv->setDelimiter(';'); $delimiter = $csv->getDelimiter(); //returns ";" ``` -------------------------------- ### Create a CSV Reader and Fetch Rows Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/reading.md Instantiate a `Reader` from a file path and iterate over its rows using the `fetch` method. Ensure the file is opened in read mode ('r'). ```php use League\Csv\Reader; $reader = Reader::createFromPath('/path/to/my/file.csv', 'r'); $results = $reader->fetch(); foreach ($results as $row) { //do something here } ``` -------------------------------- ### Delimiter Character Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/properties.md Allows setting and getting the delimiter character used in CSV files. The default is a comma (,). ```APIDOC ## Accessing and Setting CSV properties ### The delimiter character Allows setting and getting the delimiter character used in CSV files. ```php $csv->setDelimiter(';'); $delimiter = $csv->getDelimiter(); //returns ";" ``` The default delimiter character is `,`. ``` -------------------------------- ### Create CSV Writer from File Path Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/instantiation.md Instantiate a CSV Writer by providing the path to a CSV file. The default open mode is 'w'. Ensure the League\Csv\Writer class is imported. ```php use League\Csv\Reader; use League\Csv\Writer; $writer = Writer::createFromPath('/path/to/your/csv/file.csv', 'w'); ``` -------------------------------- ### Set and Get Enclosure Character Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/properties.md Configure the enclosure character for CSV parsing and retrieval. The default is '"'. ```php $csv->setEnclosure('|'); $enclosure = $csv->getEnclosure(); //returns "|" ``` -------------------------------- ### Create CSV Reader from File Path Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/instantiation.md Instantiate a CSV Reader by providing the path to a CSV file. The default open mode is 'r'. Ensure the League\Csv\Reader class is imported. ```php use League\Csv\Reader; use League\Csv\Writer; $reader = Reader::createFromPath('/path/to/your/csv/file.csv', 'r'); ``` -------------------------------- ### Handling Empty Strings with Global State (Deprecated) Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/record-mapping.md Illustrates the deprecated global state methods `allowEmptyStringAsNull` and `disallowEmptyStringAsNull` for controlling empty string to null conversion across the application. Use with caution as it affects all conversions. ```php use League\Csv\Reader; use League\Csv\Serializer\Denormalizer; $csv = Reader::fromString($document); $csv->setHeaderOffset(0); foreach ($csv->getRecordsAsObject(ClimaticRecord::class) { // the first record contains an empty string for temperature // it is converted into the null value and handle by the // default conversion type casting; } Denormalizer::disallowEmptyStringAsNull(); foreach ($csv->getRecordsAsObject(ClimaticRecord::class) { // a TypeCastingFailed exception is thrown because we // can not convert the empty string into a valid // temperature property value // which expects `null` or a non-empty string. } ``` -------------------------------- ### Get All Records as Arrays Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/index.md Retrieves all records from a CSV file as an iterator of arrays. Each record is represented by an array of strings. ```php use League\Csv\Reader; $reader = Reader::from('/path/to/my/file.csv', 'r'); $records = $reader->getRecords(); foreach ($records as $offset => $record) { //$offset : represents the record offset //var_export($record) returns something like // array( // 'john', // 'doe', // 'john.doe@example.com' // ); } ``` -------------------------------- ### Iterating over CSV data with Reader Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/upgrading.md Before version 9.0, `fetchAll` was used to get all records. Now, the `Reader` object is directly iterable. ```php use League\Csv\Reader; $reader = Reader::createFromPath('/path/to/file.csv', 'r'); foreach ($reader->fetchAll() as $key => $value) { // do something here } ``` ```php use League\Csv\Reader; $reader = Reader::createFromPath('/path/to/file.csv', 'r'); foreach ($reader as $record) { // do something here } ``` -------------------------------- ### Run Tests Source: https://github.com/thephpleague/csv/blob/master/README.md Execute the library's test suite using Composer. This includes PHPUnit, PHP CS Fixer, and PHPStan compliance tests. ```bash composer test ``` -------------------------------- ### Assign Single and Multiple Records (Static Methods) Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/record-mapping.md Use static methods Denormalizer::assign and Denormalizer::assignAll for one-time denormalization. These methods automatically use array keys as property names or allow specifying a property list. ```php setEnclosure('|'); $enclosure = $csv->getEnclosure(); //returns "|" ``` The default enclosure character is `"`. ``` -------------------------------- ### Inserting Records into a Buffer with Header Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/buffer.md Shows how to insert records into a Buffer instance that has a header. Records can be inserted as lists (if length matches header) or as associative arrays with matching keys. Insertion of incomplete or mismatched records will trigger an exception. ```php $affectedRowsCount = $buffer->insert(['first', 'second', 'third']); $buffer->last(); // returns ['column1' => 'first', 'column2' => 'second', 'column3' => 'third']; $affectedRowsCount = $buffer->insert([ 'column1' => 'first', 'column2' => 'second', 'column3' => 'third', ]); $buffer->insert(['column1' => 'first', 'column3' => 'third']); //will trigger an exception $buffer->insert(['first', 'third']); //will trigger an exception ``` -------------------------------- ### Instantiate CSV Reader and Writer from Stream Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/instantiation.md Use the `createFromStream` named constructor to instantiate League Csv Reader and League Csv Writer objects from a stream resource. The stream must be seekable. ```php use League\Csv\Reader; use League\Csv\Writer; $reader = Reader::createFromStream(fopen('/path/to/the/file.csv', 'r+')); $writer = Writer::createFromStream(fopen('php://temp', 'r+')); ``` -------------------------------- ### CastToString with Default Value Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/record-mapping.md Example of using `CastToString` to set a default value for a nullable string property when the cell value is null. ```php use League\Csv\Serializer\MapCell; #[MapCell(options: ['default' => 'Kouyaté'])] private ?string $firstname; ``` -------------------------------- ### Adding a Record Validator Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/writer/index.md Example of adding a validator to ensure a record contains exactly 10 cells. Validators are applied after formatters. ```php use League\ Csv\Writer; use League\ Csv\CannotInsertRecord; $writer->addValidator(function (array $row): bool { return 10 == count($row); }, 'row_must_contain_10_cells'); try { $writer->insertOne(['john', 'doe', 'john.doe@example.com']); } catch (CannotInsertRecord $e) { echo $e->getName(); //displays 'row_must_contain_10_cells' $e->getData();//returns the invalid data ['john', 'doe', 'john.doe@example.com'] } ``` -------------------------------- ### Using FragmentFinder to find data fragments Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/statement.md Demonstrates how to use the find, findFirst, and findFirstOrFail methods of FragmentFinder to retrieve data based on RFC7111 expressions. Note that invalid selections are skipped by find and findFirst, while findFirstOrFail throws a SyntaxError. ```php use League\Csv\Reader; use League\Csv\FragmentFinder; $reader = Reader::from('/path/to/file.csv'); $finder = new FragmentFinder(); $finder->find('row=7-5;8-9', $reader); // return an Iterator $finder->findFirst('row=7-5;8-9', $reader); // return an TabularDataReader $finder->findFirstOrFail('row=7-5;8-9', $reader); // will throw ``` -------------------------------- ### Get Pathname from CSV Reader Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/instantiation.md After instantiating a CSV Reader using a SplFileObject, you can retrieve the pathname of the underlying document using the getPathname() method. ```php use League\Csv\Reader; use League\Csv\Writer; Reader::from(new SplFileObject('/path/to/your/csv/file.csv'))->getPathname(); //returns '/path/to/your/csv/file.csv' ``` -------------------------------- ### Convert CSV to String Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/output.md Use the `toString` method to get the string representation of the CSV document. This method is recommended over `getContent` and `__toString` which are deprecated. ```php use League\Csv\Reader; $reader = Reader::from('/path/to/my/file.csv', 'r'); echo $reader->toString(); ``` -------------------------------- ### CastToBool with Default Value Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/record-mapping.md Example of using `CastToBool` to set a default boolean value for a nullable boolean property when the cell value is null. ```php use League\Csv\Serializer\MapCell; #[MapCell(options: ['default' => false])] private ?bool $isValid; ``` -------------------------------- ### Create CSV Reader from Stream Resource Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/connections/instantiation.md Create a CSV Reader from an existing stream resource. Ensure the League\Csv\Reader class is imported and the stream is opened with read/write permissions. ```php use League\Csv\Reader; use League\Csv\Writer; $reader = Reader::createFromStream(fopen('/path/to/the/file.csv', 'r+')); ``` -------------------------------- ### Filter, Sort, and Fetch CSV Data with Options Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/query-filtering.md Demonstrates using multiple query options to filter, sort, and limit CSV data before fetching it as an associative array. Includes custom filter and sort functions. ```php use League\Csv\Reader; function filterByEmail($row) { return filter_var($row[2], FILTER_VALIDATE_EMAIL); } function sortByLastName($rowA, $rowB) { return strcmp($rowB[1], $rowA[1]); } $reader = Reader::createFromPath('/path/to/file.csv', 'r'); $data = $reader ->stripBom(false) ->setOffset(3) ->setLimit(2) ->addFilter('filterByEmail') ->addSortBy('sortByLastName') ->fetchAssoc(['firstname', 'lastname', 'email'], function ($value) { return array_map('strtoupper', $value); }); // data length will be equals or lesser that 2 starting from the row index 3. // will return something like this : // // [ // ['firstname' => 'JANE', 'lastname' => 'RAMANOV', 'email' => 'JANE.RAMANOV@EXAMPLE.COM'], // ['firstname' => 'JOHN', 'lastname' => 'DOE', 'email' => 'JOHN.DOE@EXAMPLE.COM'], // ] // ``` -------------------------------- ### Instantiate CSV Reader and Writer from Path Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/instantiation.md Use the createFromPath named constructor to instantiate Reader and Writer objects from a file path or SplFileInfo object. The open mode can be specified; defaults to 'r+'. ```php use League\Csv\Reader; use League\Csv\Writer; $reader = Reader::createFromPath('/path/to/your/csv/file.csv', 'r'); //the $reader object will use the 'r+' open mode as no `open_mode` parameter was supplied. $writer = Writer::createFromPath(new SplFileObject('/path/to/your/csv/file.csv', 'a+'), 'w'); //the $writer object open mode will be 'w'!! ``` -------------------------------- ### Get Input BOM Character Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/properties.md Retrieves the BOM character detected at the beginning of the input CSV file. Returns null if no BOM is found or recognized. ```php $bom = $csv->getInputBOM(); ``` -------------------------------- ### Download XML with Custom Encoding and Formatting Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/converter/xml.md Use this snippet to download the generated XML with a custom encoding (e.g., 'iso-8859-1') and to enable XML output formatting. The `formatOutput` parameter set to `true` makes the XML more readable. Note that no validation is performed on the provided encoding string. ```php use League\Csv\Reader; use League\Csv\XMLConverter; $reader = Reader::from('file.csv'); $reader->setHeaderOffset(0); header('Cache-Control: no-cache, no-store, must-revalidate'); header('Pragma: no-cache'); header('Expires: 0'); new XMLConverter()->download( records: $reader, filename: 'generated_file.xml', encoding: 'iso-8859-1', formatOutput: true, ); die; ``` -------------------------------- ### Instantiate ResultSet from Reader Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/resultset.md Instantiate a ResultSet directly from a Reader object. Requires version 9.22.0 or later. ```php use League\Csv\ResultSet; use League\Csv\Reader; $resultSet = ResultSet::from(Reader::from('path/to/file.csv')); ``` -------------------------------- ### Fetching all rows from CSV data Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/reading.md The fetchAll method returns a sequential array containing all rows from the CSV data. It can be used to get the entire dataset at once. ```PHP $data = $reader->fetchAll(); // will return something like this : // // [ // ['john', 'doe', 'john.doe@example.com'], // ['jane', 'doe', 'jane.doe@example.com'], // ... // ] // $nb_rows = count($data); ``` -------------------------------- ### Convert League\Csv\Reader to Doctrine RecordCollection Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/extensions/doctrine.md Demonstrates how to create a Doctrine RecordCollection from a League\Csv\Reader instance, enabling the use of Doctrine Collection methods. ```php setHeaderOffset(0); $csv->setDelimiter(';'); $collection = new RecordCollection($csv); ``` -------------------------------- ### Get Records as Objects Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/tabular-data-reader.md Use getRecordsAsObject to deserialize each CSV record into instances of a specified class. This method is available for Reader and ResultSet and was added in version 9.15.0. ```php use League\Csv\Reader; $csv = Reader::fromString($document); $csv->setHeaderOffset(0); foreach ($csv->getRecordsAsObject(ClimaticRecord::class) as $instance) { // each $instance entry will be an instance of the Weather class; } ``` -------------------------------- ### Set and Get Input Encoding Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/properties.md Use `setInputEncoding` to specify the character encoding of the input CSV file and `getInputEncoding` to retrieve it. The default input encoding is 'UTF-8'. ```php use League\Csv\Reader; $csv = Reader::createFromPath('/path/to/file.csv', 'r'); $csv->setInputEncoding('iso-8859-15'); echo $csv->getInputEncoding(); //returns iso-8859-15; ``` -------------------------------- ### Reading CSV Records with Header Normalization Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/index.md Demonstrates how to create a CSV reader from a file path, set a header offset, and retrieve normalized records. The offset indicates the header row, and subsequent records are adjusted to match the header's field count, with missing fields set to null. ```php use League\Csv\Reader; $reader = Reader::from('/path/to/my/file.csv', 'r'); $reader->setHeaderOffset(0); $records = $reader->getRecords(); foreach ($records as $offset => $record) { //$offset : represents the record offset //var_export($record) returns something like // array( // 'First Name' => 'jane', // 'Last Name' => 'jane', // 'E-mail' => null // ); } ``` -------------------------------- ### Handle validation failure with InvalidRowException Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/inserting.md When validation fails, an InvalidRowException is thrown. This exception provides methods to get the name of the failed validator and the data that caused the failure. ```php public InvalidRowException::getName(void): string ``` ```php public InvalidRowException::getData(void): array ``` -------------------------------- ### Setting and Getting the Delimiter Character Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/properties.md Shows how to set a custom delimiter character for CSV files and retrieve it using the Reader class. The default delimiter is a comma. ```php use League\Csv\Reader; $csv = Reader::createFromPath('/path/to/file.csv', 'r'); $csv->setDelimiter(';'); $delimiter = $csv->getDelimiter(); //returns ";" ``` -------------------------------- ### Attaching an Iconv Stream Filter to League Csv Reader Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/filtering.md Shows how to attach a stream filter for character set conversion (e.g., UTF-8 to ASCII with transliteration) directly to a CSV reader instance. This example utilizes the iconv extension's capabilities. ```php use League\Csv\Reader; $reader = Reader::createFromPath('/path/to/my/chinese.csv', 'r'); $reader->appendStreamFilter('convert.iconv.UTF-8/ASCII//TRANSLIT'); var_dump($reader->fetchAll()); ``` -------------------------------- ### Create and Process CSV Statement Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/statement.md Use the `Statement::create` named constructor to create a statement and then process a CSV reader. The `process` method returns a `ResultSet` with applied constraints. ```php use League\Csv\Reader; use League\Csv\Statement; $reader = Reader::from('/path/to/file.csv'); $records = (new Statement())->process($reader); // $records is a League\Csv\ResultSet instance ``` -------------------------------- ### SplFileObject Flags Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/properties.md Allows setting and getting flags for the internal SplFileObject, which fine-tunes CSV parsing behavior. Specific flags can be added or removed, except for READ_CSV. ```APIDOC ### The SplFileObject flags Allows setting and getting flags for the internal SplFileObject, which fine-tunes CSV parsing behavior. ```php $csv->setFlags(SplFileObject::READ_AHEAD|SplFileObject::SKIP_EMPTY); $flags = $csv->getFlags(); //returns an integer ``` On instantiation the flags set are: `SplFileObject::READ_CSV`, `SplFileObject::READ_AHEAD`, `SplFileObject::SKIP_EMPTY`. On update you can add or remove any `SplFileObject` flags except for the `SplFileObject::READ_CSV` flag. ``` -------------------------------- ### Add and Apply a Row Formatter Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/inserting.md Illustrates adding a formatter to convert row data to uppercase before insertion and then inserting a row. ```php use League\Csv\Writer; $writer->addFormatter(function ($row) { return array_map('strtoupper', $row); }); $writer->insertOne(['john', 'doe', 'john.doe@example.com']); $writer->__toString(); //will display something like JOHN,DOE,JOHN.DOE@EXAMPLE.COM ``` -------------------------------- ### Output CSV Content as String Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/basic-usage.md Get the string representation of the entire CSV document. This can be achieved by echoing the reader object directly or by calling its __toString method. ```PHP use League\Csv\Reader; $reader = Reader::createFromPath('/path/to/my/file.csv', 'r'); echo $reader; // or echo $reader->__toString(); ``` -------------------------------- ### Handling Duplicate Header Names Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/index.md Demonstrates how the Reader class throws a SyntaxError exception if the header row contains duplicate entries. Shows how to catch the exception and retrieve the list of duplicate column names. ```php use League\Csv\Reader; use League\Csv\SyntaxError; $csv = Reader::from('/path/to/file.csv', 'r'); $csv->nth(0); //returns ['field1', 'field2', 'field1', 'field4'] $csv->setHeaderOffset(0); //valid offset but the record contain duplicates $header_offset = $csv->getHeaderOffset(); //returns 0 try { $records = $csv->getRecords(); //throws a SyntaxError exception } catch (SyntaxError $exception) { $duplicates = $exception->duplicateColumnNames(); //returns ['field1'] } ``` -------------------------------- ### Slice Tabular Data Records Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/tabular-data-reader.md Extract a specific range of records from a TabularDataReader using the `slice` method. Specify the starting offset and the number of records to retrieve. ```php use League\Csv\Reader; use League\Csv\Statement; $reader = Reader::from('/path/to/my/file.csv', 'r'); $resultSet = (new Statement())->process($reader); $records = $resultSet->slice(10, 25); //$records is a TabularDataReader which contains up to 25 rows //starting at the offset 10 (the eleventh rows) ``` -------------------------------- ### Include League\Csv Autoloader Source: https://github.com/thephpleague/csv/blob/master/docs/8.0/installation.md Include the provided autoloader script when using League Csv without Composer. Ensure the path to the library is correct. ```php use League\Csv\Reader; use League\Csv\Writer; require '/path/to/league/csv/autoload.php'; //your script starts here ``` -------------------------------- ### Instantiate CSV Reader and Writer from SplFileObject Source: https://github.com/thephpleague/csv/blob/master/docs/7.0/instantiation.md Use the createFromFileObject named constructor when you already have a SplFileObject instance to work with. ```php use League\Csv\Reader; use League\Csv\Writer; $reader = Reader::createFromFileObject(new SplFileObject('/path/to/your/csv/file.csv')); $writer = Writer::createFromFileObject(new SplTempFileObject()); ``` -------------------------------- ### Get Records with Header Offset Source: https://github.com/thephpleague/csv/blob/master/docs/9.0/reader/index.md Retrieves records from a CSV file, using the first row as headers. The output records will be associative arrays with keys from the header row. ```php use League\Csv\Reader; $reader = Reader::from('/path/to/my/file.csv', 'r'); $reader->setHeaderOffset(0); $records = $reader->getRecords(); foreach ($records as $offset => $record) { //$offset : represents the record offset //var_export($record) returns something like // array( // 'First Name' => 'jane', // 'Last Name' => 'doe', // 'E-mail' => 'jane.doe@example.com' // ); } ```