我正在使用序列化程序组件的symfony,并且有一个序列化和对象到JSON格式的示例,下一步:
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$person = new \AppBundle\Entity\Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsman(false);
// return new JsonResponse($person); // empty
$serializer = new Serializer($normalizers, $encoders);
/**
* 1 param - object to be serialized
* 2 param - proper encoder, in this case JsonEncoder
* @var [type]
*/
$jsonContent = $serializer->serialize($person, 'json');
return new Response($jsonContent);
上面的示例返回如下内容:
{"id":null,"age":99,"name":"foo","sportsman":false}
但我想知道如何做同样的,而不是CSV
JSON
答案 0 :(得分:2)
自Symfony 3.2以来添加了CSV和YAML编码器
// 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');
您可以在那里找到更多信息:https://symfony.com/blog/new-in-symfony-3-2-csv-and-yaml-encoders-for-serializer