I'm trying to use xpath to get the contents of a table.
The table looks like this
<div>
<table>
<tr class="tableheader">
<td> Stuff </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="tableheader">
<td> Stuff </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
</table>
</div>
I'm trying to pull the value of all tr[@class='indent1'] between table headers
this is what I have so far :
$elements = $xPath->query("div/table/tbody/tr[@class='tableheader']");
for ($i = 0; $i < $elements->length; $i++){
print "Node: ".$elements->item($i)->nodeValue."\n";
$siblings = $xPath->query("following-sibling::tr[@class='indent1']", $elements->item($i));
foreach ($siblings as $sibling) {
print "\t开发者_StackOverflow社区Sibling: ".$sibling->nodeValue."\n";
}
}
The expected output is
Node: Stuff
Sibling: Contents
Sibling: Contents
Node: Stuff
Sibling: Contents
Sibling: Content
s
Instead it is printing ALL tr class="indent1s" for each one.
Thanks.
EDIT:
OK maybe this helps you. Just get every sibling and check the attributes with PHP:
foreach ($siblings as $sibling) {
if (!is_null($sibling->attributes)
&& $sibling->attributes->getNamedItem('class')->nodeValue == 'indent1') {
break;
}
print "\tSibling: ".$sibling->nodeValue."\n";
}
What is your goal in general? If you just want to print out the nodes, processing the structure with SAX would be more appropriate and easier (SAX with PHP).
Or maybe XSLT but I cannot help you with that.
精彩评论