-2

How can I get the number 45 from this HTML code using XPath:

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

This is what I tried so far:

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

What I'm missing here please ?

Thanks.

roberto
  • 1
  • 2

3 Answers3

0

your @class is looking for a direct match of class="ui_bubble_rating"

You may have to use the contains() function to search within the string

//span[contains(@class,'ui_bubble_rating')]
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
  • Can I use this after `$datas[$activity]['rating'] = $rating->item(0)->getAttribute('class');` ? – roberto Aug 03 '20 at 22:03
  • Yes, that aspect won't change but remember it gets the whole class value, so you may need to `explode()` it on the space character – Scuzzy Aug 03 '20 at 23:12
0

I'd recommend the following XPath, as suggested in this question:

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

You can then retrieve the number you're looking for with a regular expression that looks for a series of digits preceded by 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
  }
}

Demo

Jeto
  • 14,596
  • 2
  • 32
  • 46
0

If I understand correctly what you're looking for, this should work:

$rating = $xp->query('//span[contains(@class,"ui_bubble_rating")]/@class');
echo explode(" bubble_",$rating[0]->textContent)[1];

Output:

45
Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45