来自curl响应的SimpleXMLElement-@attributes问题

时间:2019-03-23 09:54:11

标签: php attributes simplexml simplexml-load-string

响应中的XML代码:

<hints label="luggage">20</hints>
<hints label="handluggage">5</hints>
<hints label="landing"></hints>

此功能后响应:

$arrayResponse = json_decode(json_encode((array)simplexml_load_string($response)), true);

我有这个:

"hints" => [
    0 => "20",
    1 => "5",
    2 => [
        @attributes = [
            label => "landing"
        ]
    ]
]

键“行李”和“行李”不存在。

如何使用XML值获取 KEYS ? 示例:

[
  "luggage" => 20,
  "handluggage" => 5,
  "landing" => null
]

1 个答案:

答案 0 :(得分:1)

不使用json的解决方案:

$response = '<root><hints label="luggage">20</hints><hints label="handluggage">5</hints><hints label="landing"></hints></root>';
$a = [];
foreach (simplexml_load_string($response)->hints as $hint) {
    $value = (string)$hint;
    $a[(string)$hint['label']] = $value ?: null;
}
print_r($a);