Reputation: 5
I need to parse XML string into an array. I have 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>
I'm using SimpleXML in php
$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
)
)
)
)
how to get such array? is it possible?
[field] => Array(
[last_name] => last,
[first_name] => first,
[birth_day] => 10/10/1990,
[gender] => NULL,
....
)
I do not know how else to explain this situation. I want to index the id attribute value were. please help.
Upvotes: 0
Views: 1675
Reputation: 1040
You can go over your XML like this:
foreach ($obj->field as $field) {
...
}
$field
will be the array containing last_name, first_name, birthday and gender.
Upvotes: 0
Reputation: 193261
Simple as that (Note it uses PHP 5.3 features):
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>';
Output (null value is not shown by print_r
):
Array
(
[last_name] => last
[first_name] => first
[birth_day] => 10/10/1990
[gender] =>
)
Upvotes: 3
Reputation: 239
Try this, print_r((array)($obj));
Check examples at simple_xml_load
Upvotes: 0