这是我的XML的一部分:
<group name="General">
<property name="Farbe">rosa</property>
<property name="Breite (mm)">169</property>
<property name="...">...</property>
</group>
在我的代码中,我正在查看节点名称,如下所示:
if($nodeName == 'group') {
// How to get the children here with attributes and values?
}
我尝试使用SimpleXMLElement
,但这不起作用。
感谢您的帮助!
答案 0 :(得分:0)
使用DOMDocument你可能会像这样迭代xml(未经测试):
$strxml='<group name="General">
<property name="Farbe">rosa</property>
<property name="Breite (mm)">169</property>
</group>';
$dom=new DOMDocument;
$dom->loadXML( $strxml );
$colgroups=$dom->getElementsByTagName('group');
if( $colgroups ){
foreach( $colgroups as $group ){
echo $group->getAttribute('name');
if( $group->childNodes->length ){
foreach( $group->childNodes as $child ){
if( $child->nodeType==XML_ELEMENT_NODE ) echo $child->tagName.' '.$child->getAttribute('name').' '.$child->nodeValue;
}
}
}
}
答案 1 :(得分:0)
您可以将json_decode
与json_encode
和simplexml_load_string
将xml解析为数组
$result ='<group name="General">
<property name="Farbe">rosa</property>
<property name="Breite (mm)">169</property>
</group>';
//Will convert Object data to array
function objectToArray($object){
return json_decode(json_encode($object),true,512,0);
}
$xml = objectToArray(simplexml_load_string($result));
echo '<pre>';print_r($xml);echo '</pre>';
echo $xml['@attributes']['name'];//outputs General
echo $xml['property'][0];//outputs rosa
echo $xml['property'][1];//outputs 169
将xml字符串解析为SimpleXMLElement
的对象$result ='<group name="General">
<property name="Farbe">rosa</property>
<property name="Breite (mm)">169</property>
</group>';
$xml2 = simplexml_load_string($result);
echo '<pre>';print_r($xml2);echo '</pre>';
echo $xml2->attributes();
echo $xml2->property[0];//outputs rosa
echo $xml2->property[1];//outputs 169