2014-09-13 2 views
0

내 xpath 쿼리에서 데이터를 추출하는 방법에 의아해합니다. (나는 큰 XML 파일을 실험하고있어 첫 번째 부분을 보여립니다) 내 XML 파일이됩니다PHP에서 xpath 쿼리의 결과를 얻는 방법?

I'm all the countries: 
DOMNodeList Object 
(
    [length] => 0 
) 
1 
I'm all the countries: 
DOMNodeList Object 
(
    [length] => 0 
) 
1 
I'm all the countries: 
DOMNodeList Object 
(
    [length] => 0 
) 
1 
I'm all the countries: 
DOMNodeList Object 
(
    [length] => 0 
) 
1 

: 나는 PHP의 5.5.6을 사용하고 있는데 나는이 결과를 얻고있다

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Data> 
    <NewDataSet> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Subic Bay Weather Station</City> 
     </Table> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Laoag</City> 
     </Table> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Ninoy Aquino Inter-National Airport</City> 
     </Table> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Davao Airport</City> 
     </Table> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Clark Ab</City> 
     </Table> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Legaspi</City> 
     </Table> 
     <Table> 
      <Country>Philippines</Country> 
      <City>Romblon</City> 
     </Table> 

내가하려는 것은 xpath 쿼리를 통해 국가 태그 안에 무엇이 있는지 표시하는 것입니다. 내 코드는 다음과 같습니다

<?php 

    $reader = new XMLReader(); 
    $reader->open("countries.xml", "UTF-8"); 

    while($reader->read()){ 
     //echo var_dump($reader->nodeType), "<br/>"; 
     if($reader->nodeType == XMLReader::ELEMENT && $reader->localName == "Table"){ 
      $node = $reader->expand(); 
      $dom = new DOMDocument; 
      $xp = new DomXPath($dom); 
      $xp1 = $xp->query("//Country"); 
      echo "I'm all the countries: <pre>",print_r($xp1),"</pre>"; 

     } 

    } 

    $reader->close(); 


?> 

난 그냥에 $xp1->nodeValue 또는 $xp1->item(0)->nodeValue을 사용할 수 있습니다 $의 XP1에 대한 값을받지 못했습니다 이유를 이해하지 않습니다. 반환 된 객체가 "길이"를 돌려 주었을지라도 확실히 시도했습니다. this site에있는 예제 5를 보면이 작업을 수행 할 수있는 것처럼 보입니다. 내가 뭘 놓치고 있니?

답변

1

DOM이 비어 있으므로 결코 $node을 추가하지 마십시오. 시도 :

$reader = new XMLReader(); 
$reader->open("countries.xml", "UTF-8"); 

while($reader->read()){ 
    if($reader->nodeType == XMLReader::ELEMENT && $reader->localName == "Table"){ 
     $node = $reader->expand(); 
     $dom = new DOMDocument; 
     $n = $dom->importNode($node, true); 
     $dom->appendChild($n); 
     $xp = new DomXPath($dom); 
     $xp1 = $xp->query("//Country"); 
     echo "I'm all the countries: <pre>{$xp1->item(0)->nodeValue}</pre>"; 

    } 

} 

$reader->close(); 
+1

작동합니다! 그건 의미가 있습니다. appendChild()를 사용하는 데 혼란 스러웠다. 원본 XML 파일을 수정할 수 있다고 생각했기 때문이다.하지만 지금은 xpath를 사용할 수 있도록 DOM을 채우기 위해 그렇게하고있다. 감사! – markovchain

관련 문제