New in Symfony 3.2: CSV and YAML encoders for Serializer
October 17, 2016 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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];
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
"$data = [
'foo' => 'aaa',
'bar' => [
['id' => 111, 1 => 'bbb'],
['lorem' => 'ipsum'],
]
];
// data.csv:
// foo,bar.0.id,bar.0.1,bar.1.lorem
// aaa,111,bbb,ipsum"
From my tests, I'm getting :
foo,bar.id,bar.1,bar.lorem
aaa,111,bbb,ipsum
which is something I can rather understand.