2012-12-08 126 views
0

我剛開始使用XPath,並且正在擺弄如何正確遍歷表元素以在tr中查找td值。我試圖只回顯節點的兄弟值。我的表,例如:xPath從表中獲取值

<table class="123"> 
    <tbody> 
     <tr> 
      <td id="myYear">Year</td> 
      <td>2001</td> 
      <td>2002</td> 
      <td>2003</td> 
     </tr> 
     <tr> 
      <td id="myScores">Scores</td> 
      <td>82</td> 
      <td>87</td> 
      <td>94</td> 
     </tr> 
    </tbody> 
</table> 

我的PHP代碼如下:

$dom = new DOMDocument; 
$dom->preserveWhiteSpace = false;  
$dom->loadHTML($content); 
$xpath = new DOMXpath($dom); 

$myYear = $xpath->query('//table[@class="123"]/tbody/tr/td[@id="myYear"]'); 

foreach ($myYear as $year) { 
    echo $year->nodeValue; //returns Year 
    echo "<br>"; 

    $siblings = $year->nextSibling; 

    foreach ($siblings as $value) { 
     echo $value->nodeValue; 
    } 
} 

在上面的例子中,輸出的是「年」,但我沒有得到任何輸出爲三個兄弟值例如82,87,94的「myScores」。

感謝您的任何建議。

回答

1

一些自學在這裏!我簡單地使用下面的兄弟姐妹是這樣的:

$myYear = $xpath->query('//table[@class="123"]/tbody/tr/td[@id="myYear"]/following-sibling::*'); 

foreach ($myYear as $year) { 
    echo $year->nodeValue; //returns Year 
    echo "<br>"; 
}