PHP code example of talkingbit / csv

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

    

talkingbit / csv example snippets


use TalkingBit\Csv\Reader\Reader;

$reader = new Reader();
$filePath = '/path/to/file.csv';
$rows = $reader
    ->fromFile($filePath)
    ->readAll();

foreach ($rows as $row) {
    // Do whatever you need
}

use TalkingBit\Csv\Reader\Reader;

$reader = new Reader();
$filePath = '/path/to/file.csv';
$rows = $reader
    ->fromFile($filePath)
    ->withHeaders()
    ->readAll();

foreach ($rows as $row) {
    // Do whatever you need
}

use TalkingBit\Csv\Reader\Reader;
use TalkingBit\Csv\Reader\Mapper\DtoMapper;

$reader = new Reader();
$filePath = '/path/to/file.csv';
$rows = $reader
    ->fromFile($filePath)
    ->withHeaders()
    ->usingMapper(new DtoMapper(MyDto::class))
    ->readAll();

foreach ($rows as $row) {
    // Do whatever you need
}

use TalkingBit\Csv\Writer\Writer;

$writer = new Writer();
$writer
    ->toFile('/path/to/file.csv')
    ->writeRow([123, 'My name']);

use TalkingBit\Csv\Writer\Writer;

$writer = new Writer();
$writer
    ->toFile('/path/to/file.csv')
    ->writeRow(['id' => 123, 'name' => 'My name']);

use TalkingBit\Csv\Writer\Writer;

$writer = new Writer();

$dto = new MyDto();
$dto->id = 123;
$dto->name = 'My name';

$writer
    ->toFile('/path/to/file.csv')
    ->writeRow($dto);

$writer
    ->toFile('/path/to/file.csv')
    ->withDelimiter(',')
    ->withEnclosure('"')
    ->writeRow($dto);

interface RowMapperInterface
{
    public function map(array $line, ?array $headers = null);
}