在一系列子级中,XML:php仅解析第一个


XML: php only parsing first in a series of children

我有一个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节点的子节点。为什么我不能获取第二个的子节点?

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

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

样本输出