Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Csv Laravel Package

ajgl/csv

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ajgl/csv
    

    No additional configuration is required—just autoload the package.

  2. First Use Case:

    • Reading a CSV:
      use Ajgl\Csv\Reader;
      
      $reader = new Reader('path/to/file.csv');
      $rows = $reader->getRows(); // Returns associative array of rows
      
    • Writing a CSV (RFC 4180 compliant):
      use Ajgl\Csv\Writer;
      
      $writer = new Writer('path/to/output.csv');
      $writer->insertRow(['col1', 'col2', 'col3']);
      $writer->insertRow(['data1', 'data2', 'data3']);
      $writer->close(); // Flushes remaining data
      
  3. Where to Look First:

    • Usage Examples in the README.
    • Ajgl\Csv\Reader and Ajgl\Csv\Writer classes for core functionality.
    • Ajgl\Csv\Rfc4180\Reader/Writer for strict RFC 4180 compliance.

Implementation Patterns

Core Workflows

  1. Reading CSV Data:

    • Streaming Large Files: Use getRows() with a callback for memory efficiency:
      $reader = new Reader('large_file.csv');
      $reader->getRows(function ($row) {
          // Process row-by-row (avoids loading entire file into memory)
      });
      
    • Header Handling: Extract headers from the first row:
      $headers = array_shift($reader->getRows());
      
  2. Writing CSV Data:

    • Batch Inserts:
      $writer = new Writer('output.csv');
      foreach ($data as $row) {
          $writer->insertRow($row);
      }
      $writer->close();
      
    • Custom Delimiters/Enclosures: Use the Rfc4180\Writer for strict compliance or override defaults:
      $writer = new Writer('output.csv', ',', '"', '\\');
      
  3. Integration with Laravel:

    • Service Provider Binding: Bind the reader/writer to the container for dependency injection:
      $this->app->bind('csv.reader', function () {
          return new Reader(config('csv.path'));
      });
      
    • Artisan Commands: Process CSV files via CLI:
      use Ajgl\Csv\Reader;
      
      class ImportCommand extends Command {
          protected function handle() {
              $reader = new Reader(storage_path('app/import.csv'));
              // Process rows...
          }
      }
      
  4. Validation & Transformation:

    • Validate rows before writing:
      $writer = new Writer('output.csv');
      foreach ($data as $row) {
          if ($this->isValidRow($row)) {
              $writer->insertRow($this->transformRow($row));
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Memory Management:

    • Avoid loading large CSV files entirely into memory. Use streaming (getRows() with a callback) for files >1MB.
    • Fix: Process rows in chunks or use generators.
  2. Encoding Issues:

    • Non-UTF-8 files may corrupt data. Explicitly set encoding when reading/writing:
      $reader = new Reader('file.csv', ',', '"', '\\', 'ISO-8859-1');
      
  3. Line Endings:

    • Windows (\r\n) vs. Unix (\n) line endings can cause parsing errors. Use Rfc4180\Writer for consistency.
  4. Closed Writers:

    • Always call $writer->close() to flush buffered data. Forgetting this may truncate output files.
  5. Deprecated Methods:

    • The package is archived (last release: 2020). Some methods may lack PHP 8+ support (e.g., array_merge_recursive in older PHP versions).

Debugging Tips

  1. Validate CSV Structure:

    • Use Rfc4180\Reader to enforce strict compliance:
      $reader = new \Ajgl\Csv\Rfc4180\Reader('file.csv');
      try {
          $rows = $reader->getRows();
      } catch (\Ajgl\Csv\Exception\CsvException $e) {
          // Handle malformed CSV (e.g., unescaped delimiters)
      }
      
  2. Log Warnings:

    • Wrap CSV operations in try-catch blocks to log errors:
      try {
          $writer->insertRow($row);
      } catch (\Exception $e) {
          Log::warning("CSV write failed: " . $e->getMessage());
      }
      
  3. Test Edge Cases:

    • Test with:
      • Empty files.
      • Files with only headers.
      • Files with escaped delimiters ("field, with, commas").
      • Multiline fields (RFC 4180 allows this).

Extension Points

  1. Custom Writers/Readers:

    • Extend Ajgl\Csv\AbstractReader/AbstractWriter for custom logic:
      class MyReader extends \Ajgl\Csv\AbstractReader {
          public function getRows() {
              $rows = parent::getRows();
              return array_map([$this, 'transformRow'], $rows);
          }
      }
      
  2. Event Hooks:

    • Override insertRow() to add pre/post-processing:
      $writer = new Writer('output.csv');
      $writer->insertRow = function ($row) {
          $row['processed_at'] = now()->toDateTimeString();
          parent::insertRow($row);
      };
      
  3. Laravel Service Providers:

    • Register macros for global CSV handling:
      Reader::macro('toCollection', function () {
          return collect($this->getRows());
      });
      
  4. Fallback for Native Functions:

    • Use the Rfc4180 implementations if fgetcsv()/fputcsv() behave unexpectedly (e.g., with complex delimiters).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style