0

php Symfony serializer - Deserialize xml to array of objects

How deserialize xml with attributes to array of objects?

$string = '<?xml version="1.0" encoding="UTF-8" ?>
<response>
    <item flight="23"/>
    <item flight="24"/>
</response>';

        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);

        $serializer = new Serializer(
            [new ArrayDenormalizer(), new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter)],
            [new XmlEncoder()]
        );
$objects = $serializer->deserialize($string, 'App\Entities\Item[]', 'xml');

Item class:

class Item
{
    #[SerializedName('@flight')]
    public string $flight;
}

Now result:

array:1 [
  "item" => App\Entities\Item
]

1 Answer 1

0

You must enter the square brackets twice.

$objects = $serializer->deserialize($string, 'App\Tests\Item[][]', 'xml')

enter image description here

Or the following. But it is basically the same thing.

$xmlContent = '
    <response>
        <item flight="23"/>
        <item flight="24"/>
    </response>
';

class Item
{
    public string $flight;

    /**
     * @param string $flight
     */
    public function __construct(string $flight)
    {
        $this->flight = $flight;
    }

    /**
     * @return string
     */
    public function getFlight(): string
    {
        return $this->flight;
    }
}

$flights = [];
$encoders = [new XmlEncoder()];
$serializer = new Serializer([], $encoders);
$response = $serializer->decode($xmlContent, "xml");
foreach ($response['item'] as $item) {
    $flights[] = new Item($item['@flight']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

For simple decoding, you can not create a Serializer, but simply new XmlEncoder();

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.