Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version


3.4 version


Encoders basically turn arrays into formats and vice versa. They implement Symfony\Component\Serializer\Encoder\EncoderInterface for encoding (array to format) and Symfony\Component\Serializer\Encoder\DecoderInterface for decoding (format to array).

You can add new encoders to a Serializer instance by using its second constructor argument:

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;

$encoders = [new XmlEncoder(), new JsonEncoder()];
$serializer = new Serializer([], $encoders);

Built-in Encoders

The Serializer component provides built-in encoders:

  • Symfony\Component\Serializer\Encoder\CsvEncoder to encode/decode CSV
  • Symfony\Component\Serializer\Encoder\JsonEncoder to encode/decode JSON
  • Symfony\Component\Serializer\Encoder\XmlEncoder to encode/decode XML
  • Symfony\Component\Serializer\Encoder\YamlEncoder to encode/decode Yaml

New in version 3.2: The Symfony\Component\Serializer\Encoder\CsvEncoder and the Symfony\Component\Serializer\Encoder\YamlEncoder were introduced in Symfony 3.2.

The JsonEncoder

The JsonEncoder encodes to and decodes from JSON strings, based on the PHP json_encode and json_decode functions.

The XmlEncoder

This encoder transforms arrays into XML and vice versa.

For example, take an object normalized as following:

['foo' => [1, 2], 'bar' => true];

The XmlEncoder will encode this object like that:

<?xml version="1.0"?>

Be aware that this encoder will consider keys beginning with @ as attributes:

$encoder = new XmlEncoder();
$encoder->encode(['foo' => ['@bar' => 'value']]);
// will return:
// <?xml version="1.0"?>
// <response>
//     <foo bar="value"/>
// </response>

The YamlEncoder

This encoder requires the Yaml Component and transforms from and to Yaml.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.