2014-09-13 85 views
0

我很困惑如何從我的xpath查詢中提取數據。我使用PHP 5.5.6,我得到這個結果:如何在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 

我的XML文件(截斷,只顯示了第一部分,我與大的XML文件試驗):

<?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查詢顯示Country標籤內的內容。我的代碼是:

<?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一個值,我可以只上使用$xp1->nodeValue$xp1->item(0)->nodeValue。我已經嘗試過,即使返回的對象只有「長度」才能返回。我在看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文件,但我現在看到我只是這樣做來填充我的DOM,所以我可以使用xpath。謝謝! – markovchain 2014-09-13 18:12:26