PHP code example of wilgucki / php-csv

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

    

wilgucki / php-csv example snippets


$reader = new Reader();
$reader->open('/path/to/file.csv');

$reader = new Reader();
$reader->open('/path/to/file.csv');
$reader->addConverter(3, new DateToCarbon());
$data = $reader->readLine();

$reader = new Reader();
$reader->open('/path/to/file.csv');
print_r($reader->readLine());
/*
Array
(
    [0] => user_id
    [1] => name
)
*/
print_r($reader->readLine());
/*
Array
(
    [0] => 1
    [1] => john
)
*/


$reader = new Reader();
$reader->open('/path/to/file.csv');
print_r($reader->readAll());
/*
Array
(
    [0] => Array
        (
            [0] => user_id
            [1] => name
        )

    [1] => Array
        (
            [0] => 1
            [1] => john
        )

    [2] => Array
        (
            [0] => 2
            [1] => jane
        )

)
*/

$reader = new Reader();
$reader->open('/path/to/file.csv');
print_r($reader->getHeader());
/*
Array
(
    [0] => user_id
    [1] => name
)
*/


$reader = new Reader();
$reader->open('/path/to/file.csv');
$reader->getHeader();
print_r($reader->readLine());
/*
Array
(
    [user_id] => 1
    [name] => john
)
*/


$reader = new Reader();
$reader->open('/path/to/file.csv');
$reader->getHeader();
print_r($reader->readAll());
/*
Array
(
    [0] => Array
        (
            [user_id] => 1
            [name] => john
        )

    [1] => Array
        (
            [user_id] => 2
            [name] => jane
        )

)
*/


$reader->close();

$writer = new Writer();

// create new file
$writer->create('/path/to/file.csv');

// update existing file
$writer->create('/path/to/file.csv', 'a+');

// write a single line to the CSV file

$writer = new Writer();
$writer->create('/path/to/file.csv');
$writer->writeLine(['abc', 'def']);

// write multiple lines to the CSV file

$writer = new Writer();
$writer->create('/path/to/file.csv');
$writer->writeAll([
    ['abc', 'def'],
    [123, 234]
]);

// display added data

$writer = new Writer();
$writer->create('/path/to/file.csv');
$writer->writeAll([
    ['abc', 'def'],
    [123, 234]
]);
echo $writer->flush();
/*
abc,def
123,234
*/

$writer->close();

composer