jjoselon jjoselon - 24 days ago 10
PHP Question

How to encoder Csv with Symfony

I'm using serializer component's symfony, and there was an example to serialize and Object to JSON format, next:

$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);


The above example returns something like this:

{"id":null,"age":99,"name":"foo","sportsman":false}


But I want know How to do the same, to
CSV
instead
JSON

Answer Source

CSV and YAML encoder were added since Symfony 3.2

// 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');

You can find more info there: https://symfony.com/blog/new-in-symfony-3-2-csv-and-yaml-encoders-for-serializer