2017-04-25 20 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) ; 

// 당신은 관련 요소를 얻기 위해 XPath 쿼리를 사용할 수 있습니다

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

childNode에에서 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

이 피나 lly는 작동 시키지만 추한 것입니다. 위의 제안을 사용하려고합니다. 그러나, getElementsByTagName을 childNode에서 추출 할 수 있습니까? 내 원본 게시물 하단에 몇 가지 샘플 코드를 추가했습니다. – rolinger

+0

모든 DomElement 객체에서 getElementsByTagName을 사용할 수 있습니다. 그러나 다른 문제가있는 경우 문제 해결 및 테스트를 수행 한 후 질문을 게시해야합니다. – miken32