SimpleXMLElement get first XPath Element in one line [duplicate]

一曲冷凌霜 提交于 2019-12-23 20:21:55

问题


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;

回答1:


I don't know php too well, but shouldn't:

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

be the same as

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

Edit Jul 2013: Yes it does since PHP 5.4. With the little correction I added. That means all stable (non-end-of-life) versions of PHP as of now support that.




回答2:


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:

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

Since PHP 5.4 it's more straight forward with:

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

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:

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

For PHP 5.4+ it's similar, here a benefit is the new array syntax just with square brackets:

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

See as well:

  • PHP: Access Array Value on the Fly

Note in the margin: Because you only expect one element, you should not return more than one by the xpath already:

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


来源:https://stackoverflow.com/questions/2815639/simplexmlelement-get-first-xpath-element-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!