使用domdocument读取xml文件需要用到以下几个方法和属性:
方法:
1:读取xml文件:load()
2:获取标签的对象数组:getElementByTagName()
3:对象数组的索引:item()
属性:
1:获取属性或节点的文本:nodeValue
2:获取属性名或者节点名:nodeName
2:获取该节点的子节点集合:childNodes
3:获取该节点的属性集合:attributes
实例xml文件(a.xml):
1 <?xml version="1.0 encoding="UTF-8"?> 2 <people nation="汉族" city="火星"> 3 <xiaohua college="qinghua"> 4 <name>小华</name> 5 <age>12</age> 6 <sex>男</sex> 7 </xiaohua> 8 <xiaoming college="beida"> 9 <name>小明</name> 10 <age>15</age> 11 <sex>男</sex> 12 </xiaoming> 13 <xiaoqiang college="jiaotong"> 14 <name>小强</name> 15 <age>13</age> 16 <sex>男</sex> 17 </xiaoqiang> 18 </people>
<?php $dom = new DomDocument(); $dom->load(a.xml); $people = $dom->getElementByTagName(‘people‘);//获取people的节点数组 $people->item(0);//获取第一个people节点 $people->item(0)->childNodes;//获取第一个people节点的所有子节点 $people->item(0)->attributes;//获取第一个people节点的所有属性 $people->item(0)->childNodes->item(0);//获取第一个people节点的第一个节点,即xiaohua节点 $people->item(0)->attributes->item(0);//获取第一个people节点的第一个属性,即nation属性。 $people->item(0)->childNodes->item(0)->childNodes->item(0);//获取第一个people节点的第一个节点里的name节点 echo $people->item(0)->attributes->item(0)->nodeName;//输出字符串:nation echo $people->item(0)->attributes->item(0)->nodeValue//输出字符串:汉族 echo $people->item(0)->childNodes->item(0)->childNodes->item(0)->nodeName;//输出字符串:name echo $people->item(0)->childNodes->item(0)->childNodes->item(0)->nodeValue;//输出字符串:小华 foreach($people->item(0)->attributes as $key => $value){//遍历节点 echo $key;//第一次输出字符串:nation,第二次输出字符串:city echo $value->nodeValue;//第一次输出字符串:汉族,第二次输出字符串:火星 }
时间: 2024-10-22 18:54:04