Symfony News

New in Symfony 3.2: CSV and YAML encoders for Serializer

Kévin Dunglas

Contributed by
Kévin Dunglas
in #19197 and #19326.

CSV encoder

This encoder/decoder is ideal to import/export application data to programs like Excel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// instantiation, when using it as a component
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);

// instantiation, when using it inside the Symfony framework
$serializer = $container->get('serializer');

// encoding contents in CSV format
$serializer->encode($data, 'csv');

// decoding CSV contents
$data = $serializer->decode(file_get_contents('data.csv'), 'csv');

When decoding CSV contents, the first line must be the header with the names of the columns, which will be transformed into the object properties.

The CSV encoder/decoder also supports complex and nested data structures:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$data = [
    'foo' => 'aaa',
    'bar' => [
        ['id' => 111, 1 => 'bbb'],
        ['lorem' => 'ipsum'],
    ]
];

file_put_contents(
    'data.csv',
    $container->get('serializer')->encode($data, 'csv')
);

// data.csv:
// foo,bar.0.id,bar.0.1,bar.1.lorem
// aaa,111,bbb,ipsum

YAML encoder

This encoder uses the well-known YAML parser/dumper provided by the Symfony Yaml component. Define the optional third argument of encode() and decode() to define the value of the YAML flags, the indentation spaces, etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$obj = new \stdClass();
$obj->bar = 2;

$data = $this->container->get('serializer')->encode(
    ['foo' => $obj],
    'yaml'
    // these are the default values applied by the encoder
    ['yaml_inline' => 1, 'yaml_indent' => 4, 'yaml_flags' => 0]
);
// $data = '    foo: !php/object:O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}\n';

$data = $this->container->get('serializer')->decode(
    'foo: !php/object:O:8:"stdClass":1:{s:3:"bar";i:2;}',
    'yaml'
);
// $data = ['foo' => $obj];

$data = $this->container->get('serializer')->decode(
    'foo: !php/object:O:8:"stdClass":1:{s:3:"bar";i:2;}',
    'yaml',
    ['yaml_flags' => 0]
);
// $data = ['foo' => null];

Be trained by Symfony experts - 2016-10-17 Paris - 2016-10-24 Paris - 2016-10-24 Lyon


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook