How set encoding UTF-8 and the xmlns attribute in Symfony XmlEncoder

Viewed 4030

I use Symfony 3 Serializer and convert my objects to XML through XmlEncoder. But XmlEncoder don't have encoding type in xml prolog. How to solve this problem?

Can I add custom attribut with parameters after root element?

Is there any way to set xmlns in root element?

I need such XML output:

<?xml version="1.0" encoding="utf-8"?>
<realty-feed xmlns="http://webmaster.yandex.ru/schemas/feed/realty/2010-06">
<generation-date>2010-10-05T16:36:00+04:00</generation-date> 
...
</realty-feed>

Now I get this:

<?xml version="1.0"?>
<realty-feed>
...
</realty-feed>

My serializer code fragment:

$xmlEncoder = new XmlEncoder('realty-feed');
$normalizer = new CustomNormalizer();
$serializer = new Serializer(array($normalizer),array($xmlEncoder));
$output = $serializer->serialize($objectData, 'xml');
4 Answers
<?php
$xmlEncoder = new XmlEncoder('realty-feed');
$xml = $xmlEncoder->encode([
    '@xmlns'          => 'http://webmaster.yandex.ru/schemas/feed/realty/2010-06',
    'generation-date' => '2010-10-05T16:36:00+04:00',
], 'xml');
echo $xml;

First create XmlEncoder with root node name (in your case it would be "realty-feed"):

$encoder = new XmlEncoder("realty-feed");

Than generate Xml file:

$xml = $encoder->encode([], 'xml', ['xml_encoding' => 'utf-8']);

Where first argument: - array with your xml structure and data

Second: - format

Third: - context properties (in your case xml_enxoding)

UPD:

Method for setting attributes to xls root element. Work perfectly. !Take into consideration return type hinting (its only for PHP 7+)

/**
 * Add params to xml root element
 *
 * @param $xml
 * @return SimpleXMLElement
 */
private function setXmlParams(SimpleXMLElement $xml): SimpleXMLElement
{
    $xml = new \SimpleXMLElement($xml);
    $xml->addAttribute('xmlns:xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
    $xml->addAttribute('xmlns:xmlns:xsd', "http://www.w3.org/2001/XMLSchema");
    $xml->addAttribute('xmlns', "http://localhost/example");

    return $xml;
}

Output root element:

<Root 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     xmlns="http://localhost/example"
>

On {"symfony/serializer": "^5.0"} version I was able to add those attributes in the following way:

$encoder = new XmlEncoder();
$nodes = ['@xmlns' => 'http://webmaster.yandex.ru/schemas/feed/realty/2010-06',
          'generation-date' => '2010-10-05T16:36:00+04:00'];
$xmlString = $encoder->encode($nodes, 'xml', [
    XmlEncoder::ROOT_NODE_NAME => 'realty-feed',
    XmlEncoder::ENCODING       => 'UTF-8',
]); 
echo $xmlString;

Also tried the following way which did NOT work:

$encoder = new XmlEncoder([
XmlEncoder::ROOT_NODE_NAME => $rootNodeName,
XmlEncoder::ENCODING       => $encoding,
'@xmlns' => 'http://webmaster.yandex.ru/schemas/feed/realty/2010-06',
]);

echo $encoder->encode($nodes, 'xml');
Related