PHP code example of belguinan / csv-simple-reader

1. Go to this page and download the library: Download belguinan/csv-simple-reader 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/ */

    

belguinan / csv-simple-reader example snippets


use Belguinan\CsvExporter;

// Initialize
$csv = new CsvExporter();

// Read CSV file
foreach ($csv->readFrom('path/to/file.csv') as $row) {
    var_dump($row);
}

$csv = new CsvExporter();

// Read file line by line (memory efficient)
foreach ($csv->readFrom('input.csv') as $row) {
    // $row is an array containing the CSV columns
    var_dump($row);
}

// Your data as array
$data = array(
    array('John', 'Doe', '[email protected]'),
    array('Jane', 'Smith', '[email protected]')
);

// Optional headers
$headers = array('First Name', 'Last Name', 'Email');

// Create CSV exporter
$csv = new CsvExporter($data, $headers);

// Process and save
$csv->process()->save('output.csv');

// Create and force download
$csv = new CsvExporter($data, $headers);
$csv->process()->download('users-export');

// Process, download, and save in one go
$csv->process()
    ->download('export-file')
    ->save('backup/export.csv');

try {
    $csv = new CsvExporter($data);
    $csv->process()->save('output.csv');
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}

   // Good - Memory efficient
   foreach ($csv->readFrom('large.csv') as $row) {
       processRow($row);
   }
   

   // Explicit headers
   $headers = array('ID', 'Name', 'Email');
   $csv = new CsvExporter($data, $headers);

   // Auto-generated headers from data keys
   $csv = new CsvExporter($data);
   

   try {
       $csv->readFrom('file.csv');
   } catch (\Exception $e) {
       log_error($e->getMessage());
       // Handle error appropriately
   }
   

// Fetch users from database
$users = $db->query('SELECT id, name, email FROM users');

// Convert to array
$data = array();
while ($row = $users->fetch_assoc()) {
    $data[] = $row;
}

// Export
$csv = new CsvExporter($data);
$csv->process()->download('users-export');

$csv = new CsvExporter();
$chunk = array();

foreach ($csv->readFrom('large-file.csv') as $index => $row) {
    $chunk[] = $row;
    
    // Process in chunks of 1000
    if (count($chunk) >= 1000) {
        processChunk($chunk);
        $chunk = array();
    }
}

// Process remaining rows
if (!empty($chunk)) {
    processChunk($chunk);
}