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 right now. I simply want the value without having to access the [0]
element of the result and cast to a string.
Is this possible?
You can write it most simply like this:
The
@
operator will suppress errors, making$string
null if$array
is empty.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 withDOMDocument
. In any case other users go here looking for a solution in SimpleXML it works a little differently:The element in
$first
if notNULL
(for no elements) then still will be of typeSimpleXMLElement
(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 withecho
:probably
?
if
$array[0]
is an array, you can rename string to new_arrayUsing 'evaluate' instead of 'query', you can do things like casting.
DOMXPath::evaluate()
Also, if you're just annoyed with doing stuff a lot of times, just write a function that does it ... that is the whole idea behind functions, right?
That is possible with XPath's
string
functionand DOMXPath's
evaluate
method:Example:
You can use the
position
function:Example:
or the abbreviated syntax
Note that when querying for descendants with // using the position function might yield multiple result due to the way the expression is evaluated.