Encoders
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.2 (the current stable version).
Encoders basically turn arrays into formats and vice versa. They implement EncoderInterface for encoding (array to format) and DecoderInterface for decoding (format to array).
You can add new encoders to a Serializer instance by using its second constructor argument:
1 2 3 4 5 6
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:
- CsvEncoder to encode/decode CSV
- JsonEncoder to encode/decode JSON
- XmlEncoder to encode/decode XML
- YamlEncoder to encode/decode Yaml
3.2
The CsvEncoder and the 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:
1
['foo' => [1, 2], 'bar' => true];
The XmlEncoder
will encode this object like that:
1 2 3 4 5 6
<?xml version="1.0"?>
<response>
<foo>1</foo>
<foo>2</foo>
<bar>1</bar>
</response>
Be aware that this encoder will consider keys beginning with @
as attributes:
1 2 3 4 5 6 7
$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.