[英]xPath to get values from table
我剛剛開始使用XPath,並且在擺弄如何正確遍歷表元素以在tr中找到td值。 我試圖只回顯該節點的同級值。 我的桌子,例如:
<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;
}
}
在上面的示例中,輸出為“ Year”,但是對於“ myScores”的三個同級值(例如82,87,94),我沒有任何輸出。
感謝您的任何建議。
一些自學正在進行中! 我只是像這樣使用跟隨兄弟:
$myYear = $xpath->query('//table[@class="123"]/tbody/tr/td[@id="myYear"]/following-sibling::*');
foreach ($myYear as $year) {
echo $year->nodeValue; //returns Year
echo "<br>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.