This question already has an answer here:
Just trying to figure a shorter way to do this:
I'm using simpleXMLElement to parse an xml file and it's aggravating to have to call two lines to process an array when I know what node I want.
Current code:
$xml = new SimpleXMLElement($data);
$r = $xml->xpath('///givexNumber');
$result["cardNum"] = $r[0];
What I would like to do would be something like I can do with DomX
$result["cardNum"] = $xml->xpath('///givexNumber')->item(0)->nodeValue;
I don't know php too well, but shouldn't:
be the same as
In PHP < 5.4 (which supports array dereference the result of a function or method call) you can access the first element either with the help of
list
:Since PHP 5.4 it's more straight forward with:
Take care that these only work without any notices if the xpath method returns an array with at least one element. If you're not sure about that and you need a default value this can be achieved by using the array union operator.
In PHP < 5.4 the code that has the default return value of
NULL
would be:For PHP 5.4+ it's similar, here a benefit is the new array syntax just with square brackets:
See as well: