尝试使用PHP DOMXPATH在类标记之间获取数据


try to grab data between class tag with PHP DOMXPATH

我正在尝试获取html文档中两个css类标记之间的数据。

这里是一个例子。

<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>

我不知道如何获取

类heading10和heading11之间的

数据。

我试过//p[@class="heading10"]//following-sibling::p],它会在班主任10后抓取所有<p>

尝试类似的东西

//p[@class="heading10"]/following-sibling::p[position()<count(//p[@class="heading11"]/preceding-sibling::p)]

编辑:

关于@jpaugh的更多解释:

OP的xpath获取在具有class="heading10"的元素之后的所有同级p元素。我增加了对这些元素的position()的限制,使其小于p元素和class="heading11"的位置。

以下代码已确认可用于php 5.5,但不适用于php 5.4(感谢@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)
}

请注意,如果<p class="heading10">不是第一个p元素,那么您可能需要减去它们:

//p[@class="heading10"]/following-sibling::p[position()<(count(//p[@class="heading11"]/preceding-sibling::p) - count(//p[@class="heading10"]/preceding-sibling::p))]

为了可读性按行拆分:

//p[@class="heading10"]
 /following-sibling::p[
     position()<(
         count(//p[@class="heading11"]/preceding-sibling::p) -
         count(//p[@class="heading10"]/preceding-sibling::p)
     )
  ]