這應該都是非常直接的,但由於某種原因它逃避了我。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 ??? –