【问题标题】:try to grab data between class tag with PHP DOMXPATH尝试使用 PHP DOMXPATH 获取类标签之间的数据
【发布时间】:2016-02-20 19:48:17
【问题描述】:

我试图在我的 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>

不知道怎么抢

类标题10 和标题11 之间的数据。

我试过//p[@class="heading10"]//following-sibling::p],它会抓取类标题10之后的所有&lt;p&gt;

【问题讨论】:

  • 我怀疑这是否可以通过 xpath 查询实现......但不要在那里引用我的话。但是,您可以抓住它上面的节点并循环遍历它的子节点 - 在类标题 10 的第一个实例之后将每个元素存储到一个数组中,并在找到类标题 11 时停止。然后,您可以根据需要使用新数组来解析 HTML。
  • Mikel,任何简单的代码。我有点迷路了。thx
  • 这就是目前为止。 $pTag1 = $tPageXpath->query('//*[@class="Heading10"]/following-sibling::p');我总共有 5 个元素。现在确定当元素到达标题 11 时如何停止该循环。

标签: php dom domxpath


【解决方案1】:

试试类似的东西

//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)
}

请注意,如果&lt;p class="heading10"&gt; 不是第一个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)
     )
  ]

【讨论】:

  • 此评论可以使用更多解释(例如它与 OP 的 xpath 有何不同)。
  • jpaugh,什么是 OP 的 xpath?我尝试了亚历克斯的建议。当我运行脚本时,它会抓取

    下面的 5 个

    元素。这有帮助吗?

  • @user2574693 "OP 的 xpath" 是问题中的那个://p[@class="heading10"]//following-sibling::p]。基本上是你的。请注意,由于拼写错误,我在问题中对其进行了编辑。
  • 嗨,Alex,感谢您提供简单的详细代码。我现在正在我的 PHP 5.4.16 上进行测试,但无法正常工作。我将尝试更新我的 php,然后再试一次。让你发帖。
  • Alex 的示例代码完美运行。我刚刚测试过了,它能够抓取我正在寻找的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多