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. 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:
$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.
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>";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.