【问题标题】:Whats the correct key/value Syntax to convert this Array with Symfony/XmlEncoder?使用 Symfony/XmlEncoder 转换此数组的正确键/值语法是什么?
【发布时间】:2019-09-25 14:38:54
【问题描述】:

我将我的请求数据构建为一个数组结构,并希望使用 symfony XmlEncoder 将我的数组编码为 XML。

所以我想我的基本部分是正确的,例如:

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

我正在寻找以下格式的编码的语法,带有属性和值:

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

我可以在数组键上使用@符号,但如何也适合值?

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

这应该是

<am attr="attrval"/>

但是如何写我也可以设置值?喜欢:

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

非常感谢您的帮助

【问题讨论】:

    标签: symfony xml-encoding


    【解决方案1】:

    使用'#' 作为标量值的索引。
    我通过查看编码器的测试找到了它。

    #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'));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 2017-10-18
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2011-12-25
      • 2020-03-20
      • 1970-01-01
      相关资源
      最近更新 更多