SimpleXMLElement gets the first XPath element on a single line

Just trying to figure out a shorter way to do this:

I am using simpleXMLElement to parse the xml file, and this makes the need to call two lines to process the 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 DomX

$result["cardNum"] = $xml->xpath('///givexNumber')->item(0)->nodeValue;
+3
source share
2 answers

I know php too poorly, but should not:

$result["cardNum"] = (new SimpleXMLElement($data))->xpath('///givexNumber')[0]

will be the same as

$xml = new SimpleXMLElement($data);
$r = $xml->xpath('///givexNumber');
$result["cardNum"] = $r[0];

Edit Jul 2013: Yes, this happens with PHP 5.4. With a little correction, I added. This means that all stable (non-end-of-life) versions of PHP now support this.

+1
source

PHP < 5.4 ( ), list:

list($result["cardNum"]) = $xml->xpath('//givexNumber');

PHP 5.4 :

$result["cardNum"] = $xml->xpath('//givexNumber')[0];

, - , xpath . , , .

PHP < 5.4 , NULL, :

list($result["cardNum"]) = $xml->xpath('//givexNumber[1]') + array(NULL);

PHP 5.4+ , - :

list($result["cardNum"]) = $xml->xpath('//givexNumber[1]') + [NULL];

:


, : , xpath:

$result["cardNum"] = $xml->xpath('//givexNumber[1]')[0];
                                               ###
+1

Source: https://habr.com/ru/post/1745033/


All Articles