PHP code example of otzy / csv-converter

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

    

otzy / csv-converter example snippets


$mapping = [
    'field two' => 'two',
    'field one' => 'one',
    'concat' => function ($fields, $source_field_index) {
        return $fields[$source_field_index['one']] . $fields[$source_field_index['two']];
    },
]

        $mapping = [
            'field two' => 'two',
            'field one' => 'one',
            'concat' => function ($fields, $source_field_index) {
                return $fields[$source_field_index['one']] . $fields[$source_field_index['two']];
            },
        ];

        // Create an instance of class and set mapping
        $converter = new CsvConverter();
        $converter->setMapping($mapping);

        // whether source CSV has a header line
        $converter->setSourceHasHeader(true);
        
        // whether we want the destination CSV to have header line
        $converter->setTargetHasHeader(true);
        
        // Call this method if you want to be sure that source file has specific fields
        $converter->setValidSourceHeader(['one', 'two', 'three']);
        
        $reader = Reader::createFromPath('source.csv');
        $reader->setDelimiter(';');
        $reader->setEscape('\\');
        $reader->setEnclosure('"');

        $writer = Writer::createFromPath('target.csv');

        $writer->setDelimiter(';');
        $writer->setEscape('\\');
        $writer->setEnclosure('"');
        
        $converter->convert($reader, $writer);
        
        // league/csv Writer does not close stream, the only way to do this is to unset the object
        unset($writer);