[英]xPath to get values from table
I am just getting started with XPath and am fiddling around with how to correctly traverse table elements to find the td values in a tr. 我刚刚开始使用XPath,并且在摆弄如何正确遍历表元素以在tr中找到td值。 I am trying to only echo out the sibling values of the node . 我试图只回显该节点的同级值。 My table, for example: 我的桌子,例如:
<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>
My php code is as follows: 我的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;
}
}
In the above example, the output is "Year" but I am not getting any output for the three sibling values of "myScores" for example 82,87,94. 在上面的示例中,输出为“ Year”,但是对于“ myScores”的三个同级值(例如82,87,94),我没有任何输出。
Thanks for any advice. 感谢您的任何建议。
Some self-learning going on here! 一些自学正在进行中! I simply used following-sibling like so: 我只是像这样使用跟随兄弟:
$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.