简体   繁体   中英

How to check if the variable of XPath is empty?

In some cases the below XPath does not have any value.

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

I tried to find if it does not contain with the empty function and $place='' without luck.

Is there any way to make this possible?

Using var_dump I get NULL .

The definition of the function extractNodeValue() is missing in your code-example. Therefore this can not be really answered, that is like a black box.

According to the var_dump in your question you need to compare if $place is identical to NULL , that is $place === NULL or is_null($place) .

Example (verbose):

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

$hasValue = $place !== NULL;

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

If you're referring to your extractNodeValue() function from your question xPath or operator two compute more than two? currently it may return:

  1. NULL - if your XPath query doesn't match anything;
  2. Empty string ( '' ) - if the XPath matches some nodes, but the attribute you provided or the node value is indeed an empty string, since both DOMElement::getAttribute and DOMNode::getValue return strings.

Anyhow, PHP empty considers both scenarios as empty, so without an example to see how you're using it, there's no way to tell where you ran out of luck.

If you don't want to distinguish the 2 cases above, my advise would be to standardize the function's output by changing it to:

function extractNodeValue($query, $xPath, $attribute = null) {
    $node = $xPath->query("//{$query}")->item(0);

    if (!$node) {
        return '';
    }

    return $attribute ? $node->getAttribute($attribute) : $node->nodeValue;
}

With this a simple validation as follow should work:

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

if (!empty($place)) {
    // do something
} else {
    // do something else
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM