XML: php 仅解析一系列 children 中的第一个
XML: php only parsing first in a series of children
我有一个 XML 字符串,我正在尝试提取 children 标签的名称。每个 child 标签是 self-closing。我正在尝试使用 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
节点的children。为什么我获取不到第二个的child个节点?
如果您尝试获取所有 <child*>
节点,您还需要迭代每个 <personal_data>
以进入内部层级:
$form_mappers = array();
foreach ($sxe->children() as $personal_data){
foreach($personal_data->children() as $child) {
$form_mappers[] = $child->getName();
}
}
我有一个 XML 字符串,我正在尝试提取 children 标签的名称。每个 child 标签是 self-closing。我正在尝试使用 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
节点的children。为什么我获取不到第二个的child个节点?
如果您尝试获取所有 <child*>
节点,您还需要迭代每个 <personal_data>
以进入内部层级:
$form_mappers = array();
foreach ($sxe->children() as $personal_data){
foreach($personal_data->children() as $child) {
$form_mappers[] = $child->getName();
}
}