PHP XPath:将查询结果评估为整数

时间:2012-12-10 18:05:03

标签: php xml xpath

写这个:

$likes = $xpath->query('//span[@class="LikesCount"]');

这是我得到的:

155 like

我想编写查询,以便number_before_like> 5

$likes = $xpath->query('

((int)substring-before(//span[@class="LikesCount"], " ")) > 5


');

跟随标记:

<div class="pin">

[...]

<a href="/pin/56787645270909880/" class="PinImage ImgLink">
    <img src="http://media-cache-ec3.pinterest.com/upload/56787645270909880_d7AaHYHA_b.jpg" alt="Krizia" data-componenttype="MODAL_PIN" class="PinImageImg" style="height: 288px;">
</a>

<p class="stats colorless">
    <span class="LikesCount"> 
        2 likes 
    </span>
    <span class="RepinsCount">
        6 repins
    </span>
</p>

[...]

</div>

2 个答案:

答案 0 :(得分:2)

你可以单独使用XPath语法,确保从图片中删除无关的空格。

$query = 'number(substring-before(normalize-space(
          //span[@class="LikesCount" 
          and substring-before(normalize-space(.), " ") > 5]), " "))';

$likes = $xpath->evaluate($query);

或者,让PHP为您付出艰苦的努力。

$query = 'number(php:functionString("intval",
          //span[@class="LikesCount"
          and php:functionString("intval", .) > 5]))';

$xpath->registerNamespace('php', 'http://php.net/xpath');
$xpath->registerPHPFunctions("intval");
$likes = $xpath->evaluate($query);

如果你要开始要求PHP做一些工作,那么使用简单查询并根据需要过滤结果可能会更容易。

foreach ($xpath->query('//span[@class="LikesCount"]') as $span) {
    $int = (int) $span->nodeValue;
    if ($int > 5) {
        echo $int;
    }
}

答案 1 :(得分:1)

我认为您的问题实际上是所选<span>中的额外空格。尝试剥离它们。例如,您可以使用normalize-space()

substring-before(normalize-space(//span[@class="LikesCount"]), " ")

在执行大于运算符之前,XPath处理器的类似计数字符串将为converted to a double。 (您可以通过number()强制执行此转换,但在这种情况下它是不必要的,并且可能因自动转换失败的相同原因而失败 - 导致空格。)

相关问题