我刚刚开始使用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。
感谢您的任何建议。
答案 0 :(得分: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>";
}