Return Object as XML Response in Symfony 7

Return Object as XML Response in Symfony 7

There are APIs which works with XML data format. It means that request and response represented in XML format. This tutorial provides example how to return object as XML response in Symfony 7 application.

Let's say we have the User class which should be returned as XML response:



namespace App\Entity;

class User
    private string $name;

    private int $age;

    public function getName(): string { return $this->name; }
    public function setName(string $name): void { $this->name = $name; }

    public function getAge(): int { return $this->age; }
    public function setAge(int $age): void { $this->age = $age; }

We created a new class which uses a Serializer component to convert a given object to XML format. An instance of the Response class is created with a corresponding Content-Type header. The new class accepts XML root node name, HTTP status code and additional headers.



namespace App\Factory;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\SerializerInterface;

class XmlResponseFactory
    public function __construct(private SerializerInterface $serializer)

    public function create(object $data, string $xmlRoot, int $status = 200, array $headers = []): Response
        return new Response(
                    XmlEncoder::ROOT_NODE_NAME => $xmlRoot,
                    XmlEncoder::ENCODING => 'UTF-8',
            array_merge($headers, ['Content-Type' => 'application/xml;charset=UTF-8'])

The new class can be used in controller as follows:



namespace App\Controller;

use App\Entity\User;
use App\Factory\XmlResponseFactory;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
    public function __construct(private XmlResponseFactory $xmlResponseFactory)

    public function index(): Response
        $user = new User();

        return $this->xmlResponseFactory->create($user, 'user');

The following response will be returned to the client:

<?xml version="1.0" encoding="UTF-8"?>

Leave a Comment

Cancel reply

Your email address will not be published.