Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
like image 736
Vladimir Monomaxxx Avatar asked Jan 19 '26 15:01

Vladimir Monomaxxx


2 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;
like image 76
tarkhov Avatar answered Jan 22 '26 19:01

tarkhov


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"
>
like image 24
Odin Thunder Avatar answered Jan 22 '26 21:01

Odin Thunder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!