netzding
netzding

Reputation: 777

Whats the correct key/value Syntax to convert this Array with Symfony/XmlEncoder?

I'm building my request data as an array structure and want to use the symfony XmlEncoder to encode my Array to XML.

I guess I got the fundamental part right, it looks like that for example:

$request_object = [
  "acc-id" => $all_credentials,
  "req-id" => $request_guid,
  "tran-type" => "spec-url"
];

The syntax I'm looking for encodes in the following format, with attribute and value:

<amount currency="EUR">1.99</amount>

I have the possibility to use the @ sign on an array key, but how do I also fit in the value?

$request_object = [
  "acc-id" => $all_credentials,
  "req-id" => $request_guid,
  "tran-type" => "spec-url"
  "am" => ["@attr"=>"attrval"] 
];

This should be:

<am attr="attrval"/>

But how to write it so that I can also set the value? like:

<am attr="attrval">VALUE</am>

Upvotes: 0

Views: 472

Answers (1)

Arleigh Hix
Arleigh Hix

Reputation: 10897

Use '#' as the index for the scalar value.
I found it by looking through the tests for the encoder.

#src:https://github.com/symfony/serializer/blob/master/Tests/Encoder/XmlEncoderTest.php  

#line: 196
public function testEncodeScalarRootAttributes()
{
    $array = [
        '#' => 'Paul',
        '@eye-color' => 'brown',
    ];
    $expected = '<?xml version="1.0"?>'."\n".
        '<response eye-color="brown">Paul</response>'."\n";
    $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
...
#line: 234
public function testEncodeScalarWithAttribute()
{
    $array = [
        'person' => ['@eye-color' => 'brown', '#' => 'Peter'],
    ];
    $expected = '<?xml version="1.0"?>'."\n".
        '<response><person eye-color="brown">Peter</person></response>'."\n";
    $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}

Upvotes: 2

Related Questions