这应该都是非常直接的,但由于某种原因它逃避了我。PHP从childNodes中提取getElementsByTagName
使用从文件导入以下XML结构:
<locations>
<devices>
<entry>
<serial>12345</serial>
<hostname>FooBarA</hostname>
<vsys>
<entry>
<displayname>CorpA</displayName>
<tag>InternalA</tag>
</entry>
</vsys>
</c>
</entry>
<entry>
<serial>123456</serial>
<hostname>FooBarB</hostname>
<vsys>
<entry>
<displayname>CorpB</displayName>
<tag>InternalB</tag>
</entry>
</vsys>
</c>
</entry>
</devices>
</locations>
并提取父母应该是直截了当:
$devices = $dom->getElementsByTagName('devices');
$data = array();
foreach($devices as $node){ // each $node = <devices> == only ONE object
foreach($node->childNodes as $child) { // each $child is the ENTIRE <entry>, including <entry> tag
// I would expect this to return the <serial> out of parent <entry>, but its not
$serial = $child->getElementsByTagName('serial') ;
echo "\n" . $count++ . ", a" .$serial->nodeName ;
if ($child->nodeName == "entry") {
// as a secondary method, I then try to extra <serial> looping through the childNodes of the parent <entry> and again, this doesn't work.
foreach ($child->childNodes as $kid) {
$serial = $kid->getElementsByTagName('serial') ;
echo ", b" .$serial->nodeName ;
}
}
}
}
上面打印出:
1a, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
2a, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
3a, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
4a, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
我实际的xml文件在serial
级别有更多的兄弟姐妹,因此它的打印所有额外的b
s ......因此,这告诉我基本的foreach正在工作,并且每个都正确地循环遍历每个级别 - 但我无法在每个级别中提取nodeName或getElementsByTagName。
我想到两种方法之一,在不同的嵌套级别,将提取<serial>
,但都没有工作。我在这里错过了什么?
我的期望是它会打印:
1a 12345, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
2a 123456, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
3a 1234567, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
4a 12345678, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b
或在miniumum:
1a, b 12345, b 12345, b 12345 ...
2a, b 123456, b 123456, b 123456 ...
3a, b 1234567, b 1234567, b 1234567 ...
etc etc.
什么是您预期的输出? –
$ child-> childNodes $ node-> childNodes ??? –