XML:php仅在一系列子代中首先解析

时间:2015-02-12 00:06:27

标签: php xml parsing simplexml

我有一个XML字符串,我试图提取子标签的名称。每个子标签都是自动关闭的。我试图使用SimpleXMLElement

$xml_str = '1<?xml version="1.0" encoding="UTF-8"?><parent><personal_data><child1 attr="sth /><child2 attr=sth2/></personal_data><personal_data><child1 attr="sth /><child2 attr=sth2/></personal_data</parent>';

$sxe = new SimpleXMLElement($xml);

//get the children from the parent
$sxe = $sxe->children();
echo $sxe;
$form_mappers = array();
foreach ($sxe->children() as $child){
    array_push($form_mappers, $child->getName());
}        

echo var_dump($form_mappers); //only children from the first parent

这只会获取第一个aParent节点的子节点。为什么我无法获得第二个子节点?

1 个答案:

答案 0 :(得分:1)

如果您尝试获取所有<child*>个节点,则还需要迭代每个<personal_data>以进入内部级别:

$form_mappers = array();
foreach ($sxe->children() as $personal_data){
    foreach($personal_data->children() as $child) {
        $form_mappers[] = $child->getName();
    }
}

Sample Output