PHP code example of vansari / php-csv

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

    

vansari / php-csv example snippets


// Reader must be construct with the existing file and it creates an Default Strategy in the constructor
$reader = new Reader($filepath);
/*
 * Default Strategy is
 * Delimiter = ',' 
 * Enclosure = '"'
 * Escape = "\\"
 * Encoding = "UTF-8"
 * hasHeader = true
 * skipEmptyLines = true
 * skipLeadingLines = 0
 * asAssociative = false (each records as ['headerfield' => value, ...])
 */

// now manipulate the strategy how to read your csv
$reader->getStrategy()
    ->setDelimiter("\t")
    ->setEncoding(CharsetEncoding::ISO_8859_1) // the encoding of the file
    ->setHasHeader(false) // if csv doesn't contain header
    ->setSkipEmptyRecords(true);

// you have also the possibility to instances a new Strategy object
$strategy = Strategy::create(); // with default values
// Than you can set the Strategy
$reader->setStrategy($strategy);

// if you want to read one Record
$record = $reader->readRecord();
// will return the first record
$nextRecord = $reader->readRecord();
// will return the next record

// you can also use an while loop
while (null !== ($record = $reader->readRecord())) {
    // ... do your stuff
}

// First instanciate a standard writer without targetpath, filename and not appending records
$writer = new Writer();
// Change the Strategy
$writer->getStrategy()
    ->setDelimiter("\t")
    ->setEncoding(CharsetEncoding::ISO_8859_1) // the encoding of the file
    ->setSkipEmptyRecords(true);

$header = [
    'column1',
    'column2',
    'column3',
];

$writer->writeHeader($header); // will return true on sucess
// Than write all Records (multidimensional array which contains each row as separate array)
$records = [
    [
        'foo' => 1,
        'bar' => 'bar',
        'baz' => 1.56,
    ],
    [
        'foo' => 'Foo Bar Man',
        'bar' => 34.98,
        'baz' => 1000,
    ],
];
$writer->writeRecords($records);
// will return true if successful otherwise false
/* content of temp file are tab separated records with header:
column1 column2 column3
1   bar 1.56
"Foo Bar Man"   34.98   1000
*/

$reader = new Reader($file);
$reader->getStrategy()
    ->setDelimiter("\t")
    ->setEncoding(CharsetEncoding::ISO_8859_1) // the encoding of the file
    ->setSkipEmptyRecords(true);

$writer = new Writer($targetPath, 'file_without_empty_lines.csv');
$writer->setStrategy($reader->getStrategy());
$writer->writeHeader($reader->getHeader());
$writer->writeRecords($reader->readAllRecords());