写这个:

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

最佳答案

您可以通过确保从图片中删除多余的空格,单独使用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;
    }
}

关于php - PHP XPath:将查询结果评估为整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13806572/

10-11 12:28
查看更多