0 follower

Final Class Yiisoft\DataResponse\Formatter\XmlFormatter

InheritanceYiisoft\DataResponse\Formatter\XmlFormatter
ImplementsYiisoft\DataResponse\Formatter\FormatterInterface

Formatter that encodes data as XML and sets appropriate response headers.

Supports arrays, traversable objects, and objects implementing Yiisoft\DataResponse\Formatter\XmlDataInterface.

Constants

Hide inherited constants

Constant Value Description Defined By
DEFAULT_ITEM_TAG_NAME 'item' Yiisoft\DataResponse\Formatter\XmlFormatter

Method Details

Hide inherited methods

__construct() public method

public __construct( string $encoding 'UTF-8', string $version '1.0', string $rootTag 'response', string $contentType 'application/xml' ): mixed
$encoding string

The character encoding for the XML document and response.

$version string

The XML version.

$rootTag string

The root element tag name. If empty, no root element is added.

$contentType string

The content type for the response.

                public function __construct(
    private readonly string $encoding = 'UTF-8',
    private readonly string $version = '1.0',
    private readonly string $rootTag = 'response',
    private readonly string $contentType = 'application/xml',
) {}

            
formatData() public method

public formatData( mixed $data ): string
$data mixed

                public function formatData(mixed $data): string
{
    if (empty($data)) {
        return '';
    }
    $dom = new DOMDocument($this->version, $this->encoding);
    if (empty($this->rootTag)) {
        $this->buildXml($dom, $dom, $data);
    } else {
        $root = new DOMElement($this->rootTag);
        $dom->appendChild($root);
        $this->buildXml($dom, $root, $data);
    }
    return (string) $dom->saveXML();
}

            
formatResponse() public method

public formatResponse( \Psr\Http\Message\ResponseInterface $response ): \Psr\Http\Message\ResponseInterface
$response \Psr\Http\Message\ResponseInterface

                public function formatResponse(ResponseInterface $response): ResponseInterface
{
    return $response->withHeader(Header::CONTENT_TYPE, "$this->contentType; charset=$this->encoding");
}