0

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>

1 Answer 1

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'));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.