0

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

so 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 im looking for encodes in the following format, with attribute and value:

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

i have the possiblity to use the @ sign on an array key, but how to 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 that i can also set the value? like:

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

help is much appreciated

netzding
  • 772
  • 4
  • 21

1 Answers1

2

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'));
}
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31