使用php从多个子子xml数据中获取所有值

时间:2017-04-30 14:52:50

标签: php xml

我从xml数据中获取值时出现问题,这是我的数据

                [a] => SimpleXMLElement Object
                    (
                        [b] => SimpleXMLElement Object
                            (
                                [id] => 123
                                [name] => Daughter
                                [a] => SimpleXMLElement Object
                                    (
                                        [b] => SimpleXMLElement Object
                                            (
                                                [id] => 234
                                                [name] => Mom 
                                                [c] => 1
                                                [a] => SimpleXMLElement Object
                                                    (
                                                        [b] => SimpleXMLElement Object
                                                            (
                                                                [id] => 345
                                                                [name] => Grandma
                                                            )

                                                    )

                                            )

                                    )

                            )

                    )

我如何获得此数据

  

123Daughter

     

234Mom

     

345Grandma

子小孩不仅很多3级,尝试阅读这个XML File - Get specific child nodes in unlimited node depths但仍然无法理解,任何人都可以帮助我,谢谢

1 个答案:

答案 0 :(得分:0)

您需要使用xpath function

$xml = simplexml_load_string($xml);
foreach ($xml->xpath('//b') as $item) {
    echo $item->id . $item->name . PHP_EOL;
}

或者如果你想打印名称:

$xml = simplexml_load_string($xml);
foreach ($xml->xpath('//name') as $name) {
    echo $name . PHP_EOL;
}

代码段:https://3v4l.org/tYeBi#output