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

标签 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>

最佳答案

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

相关文章:

php - 没有错误,但页面仍然空白并传递变量

php - 如何从数据库中删除 htmlentities() 值?

python - XML 文件偏移量和 XPath 插入元素

php - DOM loadhtml提取节点和子节点

php - 直接用php上传文件到amazon s3

PHP复选框设置为根据数据库值进行检查

java - 类内的 Xstream 类

css - xslt 中的样式标签未呈现

Android在线XML解析问题-SAX Parser

xpath - xquery随机选择文件而不重复选择