<?php
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Annotation\Groups;
$xmlEncoder = new XmlEncoder();
// Enable annotations for serializer
$classMetadataFactory = new ClassMetadataFactory(
new AnnotationLoader(new AnnotationReader())
);
$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([$normalizer], [$xmlEncoder]);
$object = new class() {
public $foo = 1;
/**
* @Groups({"text_only"})
*/
public $bar = 'text';
public $qux;
};
$serialized = $serializer->encode($object, 'xml');
echo htmlentities($serialized) . PHP_EOL;
$serialized = $serializer->encode($object, 'xml', ['groups' => ['text_only']]);
echo htmlentities($serialized);