首页 > 解决方案 > 在 PHP 中使用 XPath 从元素中获取类

问题描述

如何使用 XPath 从此 HTML 代码中获取数字 45:

<span class="ui_bubble_rating bubble_45"></span>

这是我到目前为止所尝试的:

$rating = $xp->query('//span[@class="ui_bubble_rating"]');
$datas[$activity]['rating'] = $rating->item(0)->getAttribute('class');

请问我在这里缺少什么?

谢谢。

标签: phpxpath

解决方案


我会推荐以下 XPath,正如这个问题中所建议的那样:

//span[contains(concat(" ", normalize-space(@class), " "), " ui_bubble_rating ")]

然后,您可以使用正则表达式检索您要查找的数字,该正则表达式查找前面为 的一系列数字bubble_

$ratingsElements = $xp->query('//span[contains(concat(" ", normalize-space(@class), " "), " ui_bubble_rating ")]');

if ($ratingsElements->length > 0) {
  $firstRatingElement = $ratingsElements->item(0);
  if (preg_match('/(?<=\bbubble_)\d+/', $firstRatingElement->getAttribute('class'), $matches)) {
    $datas[$activity]['rating'] = $matches[0];  // 45
  }
}

演示


推荐阅读