PHP code example of sassnowski / csv-schema

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

    

sassnowski / csv-schema example snippets




$config = [
    'schema' => [
        'first_name' => 'string',
        'last_name' => 'string',
        'age' => 'integer',
        'coolness_factor' => 'float',
    ]
];



// continuing from above..

$parser = new Sassnowski\CsvSchema\Parser($config);



public Parser::fromString(string $input): array



// Using our parser from above..

$input = "Kai,Sassnowski,26,0.3\nJohn,Doe,38,7.8";

$rows = $parser->fromString($input);

var_dump($rows[0]->firstname);
// string(3) "Kai"

var_dump($rows[0]->age);
// int(26)

var_dump($rows[0]->coolness_factor);
// float(0.3)



public Parser::fromFile(string $filename): array



// Using our parser from above..

// Assuming our file contains the same data as the string example.
$rows = $parser->fromFile('somefile.csv');

var_dump($rows[1]->firstname);
// string(4) "John"

var_dump($rows[1]->coolness_factor);
// float(7.8)



$config = [
    'delimiter' => ',',
    'enclosure' => '"',
    'escape' => '\\',
    'skipTitle' => false,
    'encoding' => 'UTF-8',
    'schema' => [ /* Your schema */ ],
];



$config = [
    'schema' => [
        'name' => 'string',
        'friends' => 'array:|'
    ],
];

$input = 'Kai Sassnowski,Lots|and|lots|of|friends';

$parser = new Sassnowski\CsvSchema\Parser($config);

$rows = $parser->fromString($input);

var_dump($rows[0])->friends);

// array(5) {
//    [0]=>
//    string(4) "Lots"
//    [1]=>
//    string(3) "and"
//    [2]=>
//    string(4) "lots"
//    [3]=>
//    string(2) "of"
//    [4]=>
//    string(7) "friends"
// }



public static registerType(string $type, callable $callback)



Parser::registerType('foo', function ($value) {
    return $value.'foo';
});

$config = [
    'schema' => [
        'custom' => 'foo'
    ]
];

$parser = new \Sassnowski\CsvSchema\Parser($config);

$rows = $parser->fromString("hello\nworld");

var_dump($rows[0]->custom);
// string(8) "hellofoo"

var_dump($rows[1]->custom);
// string(8) "worldfoo"



Parser::registerType('model', function ($value, $table) {
    // Pseudo code, assuming some library.
    return DB::table($table)->findById($value);
});

$config = [
    'schema' => [
        'author' => 'model:authors',
        'uploaded_by' => 'model:users',
    ]
];

$input = "5,13";

$parser = new \Sassnowski\CsvSchema\Parser($config);

$rows = $parser->fromString($input);

var_dump($rows[0]->author);
// object(Author)#1 (15) {
//    ["id"]=>
//    int(5)
//    ...
// }

var_dump($rows[1]->uploaded_by);
// object(User)#1 (12) {
//    ["id"]=>
//    int(13)
//    ...
// }