我循环遍历一个数组:
$objDOM->load("URL");
foreach ($objDOM->getElementsByTagName('CRPublication') as $node) {
$itemVacature = array (
'naam' => $node->getElementsByTagName('titleInformation')->item(0)->nodeValue
}
现在加载的XML节点具有动态ID。是否可以从getElementsByTagName为titleInformation的id中获取值?
我需要获取id的xml节点如下所示:
<createdBy>
<CRUser id="122"></CRUser>
</createdBy>
<modifiedBy>
<CRUser id="122"></CRUser>
</modifiedBy>
<owner>
<CRUser id="122"></CRUser>
</owner>
如你所见,我只能从这家外部公司获得身份证明。我必须将这些id转换为有意义的值。
提前致谢!
答案 0 :(得分:1)
使用具有父,子和子子结构的DOM Document
加载XML对象的循环示例。
$xml ='<?xml version="1.0" encoding="utf-8"?>
<root>
<Parent>
<child>child 1</child>
<child>child 2</child>
<child>child 3</child>
<subParent>
<Grandchild>Grandchild 1</Grandchild>
<Grandchild>Grandchild 2</Grandchild>
<Grandchild>Grandchild 3</Grandchild>
</subParent>
</Parent>
<Parent>
<child>child 4</child>
<child>child 5</child>
<child>child 6</child>
<subParent>
<createdBy>
<CRUser id="122"></CRUser>
</createdBy>
<modifiedBy>
<CRUser id="122"></CRUser>
</modifiedBy>
<owner>
<CRUser id="122"></CRUser>
</owner>
</subParent>
</Parent>
</root>';
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML($xml);
$i=0;
while(is_object($obj = $doc->getElementsByTagName("Parent")->item($i))) {
foreach($obj->childNodes as $nodename) {
if($nodename->nodeName=='subParent') {
foreach($nodename->childNodes as $subNodes) {
if($subNodes->nodeName=='owner') {
if(!empty($subNodes->childNodes['CRUser']->getAttribute("id"))) {
echo $subNodes->childNodes['CRUser']->getAttribute("id")."\n";
}
}
if($subNodes->nodeName=='createdBy') {
if(!empty($subNodes->childNodes['CRUser']->getAttribute("id"))) {
echo $subNodes->childNodes['CRUser']->getAttribute("id")."\n";
}
}
if($subNodes->nodeName=='modifiedBy') {
if(!empty($subNodes->childNodes['CRUser']->getAttribute("id"))) {
echo $subNodes->childNodes['CRUser']->getAttribute("id")."\n";
}
}
}
} else {
if(!empty($nodename->getAttribute("id"))) {
echo $nodename->getAttribute("id")."\n";
}
}
}
$i++;
}
/* Output
122
122
122
*/
检查以上示例here
的输出答案 1 :(得分:0)
使用getAttribute
假设架构是相同的修改代码。试试这个。
$objDOM->load("URL");
foreach ($objDOM->getElementsByTagName('CRPublication') as $node) {
$itemVacature = array (
'naam' => $node->getElementsByTagName('titleInformation')->item(0)->nodeValue,
'id' => $node->getElementsByTagName('titleInformation')->item(0)->getAttribute('id'),
);
}