CSV encoder ¶
这个编解码器对于把程序数据“导入/导出”为类似Excel这种格式十分理想:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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
// 在Symfony框架内部使用时的实例化
$serializer = $container->get('serializer');
// encoding contents in CSV format / 编码为CSV格式
$serializer->encode($data, 'csv');
// decoding CSV contents / 对CSV内容解码
$data = $serializer->decode(file_get_contents('data.csv'), 'csv'); |
当对CSV内容解码时,内容第一行必须是带有列名的header,它将被转换成对象属性。
CSV编解码器也支持复杂的嵌套数据结构:
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 ¶
这个编码器使用了Symfony Yaml组件提供的超有名的YAML parser/dumper。定义encode()
和decode()
可选的第三个参数,即可定义YAML旗标(flag)的值,以及缩进距离(indentation spaces),等等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $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]; |