2017-04-25 240 views
0

這讓我感到非常緊張。在我的XML文件中,我嵌套了名字相同的子項<entry>,我試圖僅獲得最高級別。如果我打電話getElementsByTagName()它抓住了所有這些,所以我解析爲直接的孩子,似乎沒有任何工作正常。PHP XML子解析問題

<locations> 
    <devices> 
    <entry> 
     <a/> 
     <b/> 
     <c> 
     <entry> 
     .. 
     </entry> 
     </c> 
    </entry> 
    <entry> 
     <a/> 
     <b/> 
     <c> 
     <entry> 
     .. 
     </entry> 
     </c> 
    </entry> 
    </devices> 
</locations> 

<? 
$path = "Export.txt" ; 
$xml = file_get_contents($path); 
$dom = new DOMDocument('1.0', 'utf-8'); 
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 

// use it as a source 
$dom->loadXML($xml) ; 

// grab all "devices" should ONLY be 1 device 
$devices = $dom->getElementsByTagName('devices'); 

$entries = array() ; 
// parse through each FIRST child...which should be the first level <entry> 
// however, the below is empty. 
for ($i = 0; $i < $devices->childNodes->length; ++$i) { 
    echo $count++ ; 
    $entries[] = $devices->childNodes->item($i); 
} 

// but I get the following error on this foreach: 
// Warning: Invalid argument supplied for foreach() in process.php 
foreach ($devices->childNodes as $node) { 
    echo "This: " . $count++ ; 
} 

// this prints "1": which is correct. 
echo sizeof($devices) ; 

//關於從childNode

foreach ($devices as $device) { 
    foreach($device->childNodes as $child) { // this should be each parent <entry> 
    $thisC = $child->getElementsByTagName('c') ; // this should be only <c> tags BUT THIS NEVER SEEMS TO WORK 
    foreach ($thisC->childNodes as $subEntry) { 
     echo $subEntry->nodeValue ; 
    } 
    } 
} 

回答

1

您可以使用XPath查詢來獲得相關元素提取getElementsByTag額外的問題:

<?php 
$dom = new DomDocument("1.0", "utf-8"); 
$dom->loadXML(file_get_contents("export.txt")); 
$xpath = new DomXPath($dom); 
$entries = $xpath->query("/locations/devices/entry"); 
$count = 0; 
// $entries is a DomNodeList 
var_dump($entries); 
foreach ($entries as $entry) { 
    //do stuff with $entry 
} 

或者,要使用你原來的方法:

<?php 
$dom = new DomDocument("1.0", "utf-8"); 
$dom->loadXML(file_get_contents("export.txt")); 
$devices = $dom->getElementsByTagName('devices'); 
$entries = []; 
foreach ($devices as $device) { 
    foreach ($device->childNodes as $child) { 
     if ($child instanceof DomElement && $child->tagName === "entry") { 
      $entries[] = $child; 
     } 
    } 
} 
// $entries is an array of DomElement 
var_dump($entries); 
foreach ($entries as $entry) { 
    //do stuff with $entry 
} 
+0

我是fina lly得到它的工作,但它是醜陋的。去上面使用你的建議。但是,是否可以從childNode中提取getElementsByTagName?我在原始文章的底部添加了更多示例代碼。 – rolinger

+0

您可以在任何DomElement對象上使用getElementsByTagName。但是,如果您有其他問題,則應在進行一些故障排除和測試後將其作爲一個整體發佈。 – miken32