如何检查XPath的变量是否为空?

时间:2013-07-04 16:13:33

标签: php xpath

在某些情况下,下面的XPath没有任何值。

$place = extractNodeValue('div[contains(@class, "fn")]/a', $xPath);

我试图找出它是否包含empty函数和$place=''没有运气。

有没有办法让这成为可能?

使用var_dump我得到NULL

2 个答案:

答案 0 :(得分:0)

代码示例中缺少函数extractNodeValue()的定义。因此,这不能真正回答,就像一个黑盒子。

根据您问题中的var_dump,您需要比较$placeidentical to NULL$place === NULL还是is_null($place)

示例(详细):

$place = extractNodeValue('div[contains(@class, "fn")]/a', $xPath);

$hasValue = $place !== NULL;

if ($hasValue) 
{
    # do something with $place
}

答案 1 :(得分:0)

如果您在问题xPath or operator two compute more than two?中提及extractNodeValue()功能,则可能会返回:

  1. NULL - 如果您的XPath查询与任何内容都不匹配;
  2. 空字符串('' - 如果XPath与某些节点匹配,但您提供的属性或节点值确实是空字符串,因为DOMElement::getAttributeDOMNode::getValue返回字符串。
  3. 无论如何,PHP empty认为这两种情况都是空的,所以如果没有一个例子来看你如何使用它,就没有办法告诉你运气不好的地方。

    如果您不想区分上述两种情况,我的建议是将功能的输出标准化为:

    function extractNodeValue($query, $xPath, $attribute = null) {
        $node = $xPath->query("//{$query}")->item(0);
    
        if (!$node) {
            return '';
        }
    
        return $attribute ? $node->getAttribute($attribute) : $node->nodeValue;
    }
    

    通过这个简单的验证应该起作用:

    $place = extractNodeValue('div[contains(@class, "fn")]/a', $xPath);
    
    if (!empty($place)) {
        // do something
    } else {
        // do something else
    }