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:

src/Entity/User.php

<?php

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.

src/Factory/XmlResponseFactory.php

<?php

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(
            $this->serializer->serialize(
                $data,
                XmlEncoder::FORMAT,
                [
                    XmlEncoder::ROOT_NODE_NAME => $xmlRoot,
                    XmlEncoder::ENCODING => 'UTF-8',
                ]
            ),
            $status,
            array_merge($headers, ['Content-Type' => 'application/xml;charset=UTF-8'])
        );
    }
}

The new class can be used in controller as follows:

src/Controller/TestController.php

<?php

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)
    {
    }

    #[Route('/')]
    public function index(): Response
    {
        $user = new User();
        $user->setName('John');
        $user->setAge(25);

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

The following response will be returned to the client:

<?xml version="1.0" encoding="UTF-8"?>
<user><name>John</name><age>25</age></user>

Leave a Comment

Cancel reply

Your email address will not be published.