Skip to content

[Serializer] Add Support for Encoding Arrays as Child <item> Elements in XML Encoder #60228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.3
Choose a base branch
from

Conversation

Deltachaos
Copy link
Contributor

@Deltachaos Deltachaos commented Apr 16, 2025

Q A
Branch? 7.3
Bug fix? no
New feature? yes
Deprecations? no
Issues
License MIT

Feature: Add Support for Encoding Arrays as Child <item> Elements in XML Encoder

This PR introduces a new option to the Symfony Serializer's XmlEncoder that allows indexed arrays to be encoded as <item> elements under a single parent element, rather than repeating the parent element for each array item.

Motivation

Currently, encoding an array like:

['person' => [
    ['firstname' => 'Benjamin', 'lastname' => 'Alexandre'],
    ['firstname' => 'Damien', 'lastname' => 'Clay'],
]]

produces the following XML:

<response>
    <person>
        <firstname>Benjamin</firstname>
        <lastname>Alexandre</lastname>
    </person>
    <person>
        <firstname>Damien</firstname>
        <lastname>Clay</lastname>
    </person>
</response>

This structure is not ideal when a clear container-child relationship is required, such as when interoperating with systems that expect such XML structures.

New Behavior

With the new XmlEncoder::ARRAY_AS_ITEM option enabled, the same data now encodes to:

<response>
    <person>
        <item key="0">
            <firstname>Benjamin</firstname>
            <lastname>Alexandre</lastname>
        </item>
        <item key="1">
            <firstname>Damien</firstname>
            <lastname>Clay</lastname>
        </item>
    </person>
</response>

Usage

$xml = $encoder->encode($data, 'xml', [
    XmlEncoder::ARRAY_AS_ITEM => true,
]);

@Deltachaos Deltachaos force-pushed the feature/numeric-items branch from 72bae95 to 1c234b2 Compare April 16, 2025 13:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants