XPATH - get single value returned instead of array php

后端 未结 5 1389
不知归路
不知归路 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:30

    Your question suggests that you are using SimpleXML because you talk about an array. However long-time ago you accepted an answer giving an answer with DOMDocument. In any case other users go here looking for a solution in SimpleXML it works a little differently:

    list($first) = $xml->xpath('//element') + array(NULL);
    

    The element in $first if not NULL (for no elements) then still will be of type SimpleXMLElement (either an element node or an attribute node depending on the xpath query), however you can just cast it to string in PHP and done or you just use it in string context, like with echo:

    echo $first;
    

提交回复
热议问题