Skip to content

Commit c3cbd06

Browse files
committed
Merge branch '7.4' into 8.0
* 7.4: Minor tweaks [Serializer] Support preserving array keys with XmlEncoder
2 parents f211654 + 4c9f94d commit c3cbd06

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

serializer/encoders.rst

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,9 @@ These are the options available on the :ref:`serializer context <serializer-cont
204204
require it. Example: ``'/(firstname|lastname)/'``
205205
``ignore_empty_attributes`` (default: ``false``)
206206
If set to true, ignores all attributes with empty values in the generated XML
207+
``preserve_numeric_keys`` (default: ``false``)
208+
If set to true, it keeps numeric array indexes (e.g. ``<item key="0">``)
209+
instead of collapsing them into ``<item>`` nodes.
207210

208211
Example with a custom ``context``::
209212

@@ -235,6 +238,45 @@ Example with a custom ``context``::
235238
// <date>2019-10-24</date>
236239
// </track>
237240

241+
Example with ``preserve_numeric_keys``::
242+
243+
use Symfony\Component\Serializer\Encoder\XmlEncoder;
244+
245+
$data = [
246+
'person' => [
247+
['firstname' => 'Benjamin', 'lastname' => 'Alexandre'],
248+
['firstname' => 'Damien', 'lastname' => 'Clay'],
249+
],
250+
];
251+
252+
$xmlEncoder->encode($data, 'xml', ['preserve_numeric_keys' => false]);
253+
// outputs:
254+
//<response>
255+
// <person>
256+
// <firstname>Benjamin</firstname>
257+
// <lastname>Alexandre</lastname>
258+
// </person>
259+
// <person>
260+
// <firstname>Damien</firstname>
261+
// <lastname>Clay</lastname>
262+
// </person>
263+
//</response>
264+
265+
$xmlEncoder->encode($data, 'xml', ['preserve_numeric_keys' => true]);
266+
// outputs:
267+
//<response>
268+
// <person>
269+
// <item key="0">
270+
// <firstname>Benjamin</firstname>
271+
// <lastname>Alexandre</lastname>
272+
// </item>
273+
// <item key="1">
274+
// <firstname>Damien</firstname>
275+
// <lastname>Clay</lastname>
276+
// </item>
277+
// </person>
278+
//</response>
279+
238280
The ``YamlEncoder``
239281
-------------------
240282

0 commit comments

Comments
 (0)