0

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

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried the same codes, but got an empty array. What is use of first $serializer variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.