PHP code example of spyrit / light-csv

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

    

spyrit / light-csv example snippets


use Spyrit\LightCsv\CsvReader;

// create the reader
$reader = new CsvReader(array(
    'delimiter' => ';', 
    'enclosure' => '"', 
    'encoding' => 'CP1252', 
    'eol' => "\r\n", 
    'escape' => "\\", 
    'bom' => false, 
    'translit' => 'translit',
    'force_encoding_detect' => false,
    'skip_empty' => false,
    'trim' => false,
));

//Open the csv file to read
$reader->open('test.csv');

//Read each row
foreach ($reader as $row) {
    // do what you want with the current row array : $row
}

//close the csv file
$reader->close();

use Spyrit\LightCsv\CsvWriter;

// create the writer
$writer = new CsvWriter(array(
    'delimiter' => ';', 
    'enclosure' => '"', 
    'encoding' => 'CP1252', 
    'enclosing_mod' => 'minimal',
    'escape_double' => true,
    'eol' => "\r\n", 
    'escape' => "\\", 
    'bom' => false, 
    'translit' => 'translit',
    'trim' => false,
));

//Open the csv file to write
$writer->open('test.csv');

//Write a row
$writer->writeRow(array('a', 'b', 'c'));

//Write multiple rows at the same time
$writer->writeRows(array(
    array('d', 'e', 'f'),
    array('g', 'h', 'i'),
    array('j', 'k', 'l'),
));

//close the csv file
$writer->close();

use Spyrit\LightCsv\Dialect;
use Spyrit\LightCsv\CsvReader;
use Spyrit\LightCsv\CsvWriter;

// create a dialect with some CSV parameters
$dialect = new Dialect(array(
    'delimiter' => ';', 
    'enclosure' => '"', 
    'enclosing_mode' => 'minimal',
    'encoding' => 'CP1252', 
    'eol' => "\r\n", 
    'escape' => "\\", 
    'escape_double' => true,
    'bom' => false, 
    'translit' => 'translit',
    'force_encoding_detect' => false,
    'skip_empty' => false,
    'trim' => false,
);

// change a parameter
$dialect->setLineEndings("\n");

// create the reader
$reader = new CsvReader($dialect);

//or a writer
$writer = new CsvWriter($dialect);

bash
curl -s https://getcomposer.org/installer | php
bash
php composer.phar 
bash
php composer.phar install