我需要将XML字符串解析成一个数组。我有XML
<group xmlns="123" id="personal">
<field id="last_name">last</field>
<field id="first_name">first</field>
<field id="birth_day">10/10/1990</field>
<field id="gender"/>
</group>
我在php 中使用SimpleXML
$obj = simplexml_load_string($xml_string);
var_dump($obj);
SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => personal
)
[field] => Array
(
[0] => first
[1] => last
[2] => 10/10/1990
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => gender
)
)
)
)
如何获得这样的数组?有可能吗?
[field] => Array(
[last_name] => last,
[first_name] => first,
[birth_day] => 10/10/1990,
[gender] => NULL,
....
)
我不知道该如何解释这种情况。我想索引id属性值was。请帮忙。
就这么简单(注意它使用了PHP 5.3功能):
libxml_use_internal_errors(true); // Turn off warnings because of invalid '123' namespace
$obj = simplexml_load_string($xml);
$obj->registerXPathNamespace('ns', '123');
$fields = $obj->xpath('//ns:field');
libxml_clear_errors(); // Clear warnings buffer
$result = array();
array_walk($fields, function($el) use (&$result) {
$result[(string)$el['id']] = (string)$el ?: null;
});
echo '<pre>'; print_r($result); echo '</pre>';
输出(print_r
未显示零值):
Array
(
[last_name] => last
[first_name] => first
[birth_day] => 10/10/1990
[gender] =>
)
试试这个,print_r((array)($obj));
检查simple_xml_load 上的示例
您可以这样查看XML:
foreach ($obj->field as $field) {
...
}
$field
将是包含last_name、first_name、生日和性别的数组。