XPATH - get single value returned instead of array php

后端 未结 5 1361
不知归路
不知归路 2021-01-15 01:02

I am using Xpath in PHP - I know that my query will return either 0 or 1 results.

If 1 result is returned I do not want it as an array - which is what is returned ri

5条回答
  •  无人及你
    2021-01-15 01:15

    If 1 result is returned I dont want it as an array - which is what is returned. I simply want the value without having to access the [0] element of the result and cast to a string.

    That is possible with XPath's string function

    A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

    and DOMXPath's evaluate method:

    Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

    Example:

    $dom = new DOMDocument;
    $dom->loadXML('');
    $xp = new DOMXPath($dom);
    var_dump($xp->evaluate('string(/root/@foo)')); // string(3) "bar"
    

    If there was a built in xpath way of grabbing the first and only the first node value then that would be much more preferable over writing a function to do it

    You can use the position function:

    The position function returns a number equal to the context position from the expression evaluation context.

    Example:

    $dom = new DOMDocument;
    $dom->loadXML('');
    $xp = new DOMXPath($dom);
    var_dump($xp->evaluate('string(/root/foo[position() = 1]/@xml:id)')); // string(2) "f1"
    

    or the abbreviated syntax

    $dom = new DOMDocument;
    $dom->loadXML('');
    $xp = new DOMXPath($dom);
    var_dump($xp->evaluate('string(/root/foo[1]/@xml:id)')); // string(2) "f1"
    

    Note that when querying for descendants with // using the position function might yield multiple result due to the way the expression is evaluated.

提交回复
热议问题