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
]
You must enter the square brackets twice.
$objects = $serializer->deserialize($string, 'App\Tests\Item[][]', 'xml')
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']);
}