【问题标题】:Nested SimpleXML Attributes To Associative Array将 SimpleXML 属性嵌套到关联数组
【发布时间】:2015-07-01 06:26:44
【问题描述】:

我正在将支付网关集成到网站中,他们的 API 返回一个 xml 对象,其中嵌套了我需要的值。

SimpleXMLElement Object
(

    [form] => SimpleXMLElement Object
        (
            [input] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [type] => hidden
                                    [name] => SessionStored
                                    [value] => True
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [type] => hidden
                                    [name] => SessionStoredError
                                    [value] => 
                                )

                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [type] => hidden
                                    [name] => SST
                                    [value] => e19e8abe-a2d6-4ce7
                                )

                        )

                )

        )

)

使用php如何将嵌套属性放入如下格式的关联数组中?

$array['SessionStored'] = 'True'
$array['SessionStoredError'] = ''
$array['SST'] = 'e19e8abe-a2d6-4ce7'

有点乱,但是在网上阅读了其他文章后,我整理了以下内容,这会引发“致命错误:调用成员函数属性()”

$xmlData = simplexml_load_string($result);
$aXml = json_decode( json_encode($xmlData) , 1);

$testArray = $aXml['form']['input'];

for($i = 0; $i < count($testArray); $i++)
{
    foreach($testArray[$i]->attributes() as $a => $b) {
        echo $a,'="',$b,"\"\n";
    }
}

【问题讨论】:

  • @JimGarrison 我已经添加了我当前的代码

标签: php arrays xml simplexml xml-attribute


【解决方案1】:

不要尝试转换 XML。

将 XML 转换为 JSON 意味着丢失信息。泛型转换不使用语义结构。您没有“嵌套属性”,只有一些带有属性节点的输入元素节点。

读取它并从数据中生成数组。

$result = [];
$element = new SimpleXMLElement($xml);
foreach ($element->form->input as $input) {
  $result[(string)$input['name']] = (string)$input['value'];
}

var_dump($result);

输出:

array(3) {
  ["SessionStored"]=>
  string(4) "True"
  ["SessionStoredError"]=>
  string(0) ""
  ["SST"]=>
  string(18) "e19e8abe-a2d6-4ce7"
}

使用 DOM 也很容易:

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$result = [];
foreach ($xpath->evaluate('//form/input') as $input) {
  $result[$input->getAttribute('name')] = $input->getAttribute('value');
}

var_dump($result);

【讨论】:

  • 这正是我所追求的。我今天学了些新东西。谢谢
猜你喜欢
  • 2012-07-11
  • 2014-10-11
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多