简体   繁体   中英

How to parse XML (SimpleXML)

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.

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] => 
)

Try this, print_r((array)($obj));

Check examples at simple_xml_load

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM