PHP code example of csvtoolkit / fastcsv

1. Go to this page and download the library: Download csvtoolkit/fastcsv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

csvtoolkit / fastcsv example snippets


// Create reader with file path
$reader = new FastCSVReader('/path/to/file.csv');

// Or with configuration object
$config = new FastCSVConfig();
$config->delimiter = ';';
$config->quote = '"';
$reader = new FastCSVReader($config);
$reader->open('/path/to/file.csv');

// Read records
while ($reader->hasNext()) {
    $record = $reader->nextRecord();
    print_r($record);
}

// Navigation methods
$reader->rewind();
$reader->seek(100);
$position = $reader->getPosition();
$count = $reader->getRecordCount();
$headers = $reader->getHeaders();

// Create writer with headers
$config = new FastCSVConfig();
$config->setPath('/path/to/output.csv');
$writer = new FastCSVWriter($config, ['Name', 'Age', 'City']);

// Write records (auto-flushed by default)
$writer->writeRecord(['John Doe', '30', 'New York']);
$writer->writeRecord(['Jane Smith', '25', 'Los Angeles']);

// For high-performance scenarios, disable auto-flush
$config->setAutoFlush(false);
$writer = new FastCSVWriter($config, ['ID', 'Data']);

for ($i = 0; $i < 100000; $i++) {
    $writer->writeRecord([$i, "Data$i"]);
    
    // Manual flush every 1000 records for optimal performance
    if ($i % 1000 == 0) {
        $writer->flush();
    }
}

$writer->close(); // Final flush on close

$config = new FastCSVConfig();
$config->setDelimiter(';');      // Field delimiter (default: ',')
$config->setEnclosure('"');      // Quote character (default: '"')
$config->setEscape('\\');        // Escape character (default: '\\')
$config->setHasHeader(true);     // First row contains headers (default: true)
$config->setAutoFlush(true);     // Auto-flush after each write (default: true)
$config->setStrictMode(false);   // Strict quoting mode (default: false)
$config->setSkipEmptyLines(false); // Skip empty lines (default: false)
$config->setTrimFields(false);   // Trim whitespace from fields (default: false)
$config->setWriteBOM(false);     // Write BOM for Unicode files (default: false)

dl('fastcsv.so'); // Linux/macOS
dl('fastcsv.dll'); // Windows
ini
extension=fastcsv