I am trying to grab the data between two css class tag in my html doc.
Here the example.
<p class="heading10">text text</p>
<p>text text text</p>
<p>text text text</p>
<p class="heading11">text text</p>
<p></p>
<p></p>
I don't know how to grab the
data between thatclass heading10 and heading11.
I tried //p[@class="heading10"]//following-sibling::p]
, it will grab all <p>
after the class heading10.
Try something like
//p[@class="heading10"]/following-sibling::p[position()<count(//p[@class="heading11"]/preceding-sibling::p)]
EDIT:
A bit more explanations for @jpaugh:
The OP's xpath grabs all sibling p
elements after the one with class="heading10"
. I have added the restriction for position()
of the these elements to be less than position of the p
element with class="heading11"
.
Following code is confirmed to be working with php 5.5, and does not work with php 5.4(thanks @slphp):
$t = '<?xml version="1.0"?>
<root><p class="heading10">text text</p>
<p>text text text</p>
<p>text text text</p>
<p class="heading11">text text</p>
<p></p>
<p></p></root>';
$d = DOMDocument::LoadXML($t);
$x = new DOMXpath($d);
var_dump($x->query('//p[@class="heading10"]/following-sibling::p[position()<count(//p[@class="heading11"]/preceding-sibling::p)]'));
class DOMNodeList#6 (1) {
public $length =>
int(2)
}
Please note, that if <p class="heading10">
is not the first p
element, than you probably need to subtract them:
//p[@class="heading10"]/following-sibling::p[position()<(count(//p[@class="heading11"]/preceding-sibling::p) - count(//p[@class="heading10"]/preceding-sibling::p))]
Splitting by lines for the sake of readability:
//p[@class="heading10"]
/following-sibling::p[
position()<(
count(//p[@class="heading11"]/preceding-sibling::p) -
count(//p[@class="heading10"]/preceding-sibling::p)
)
]