SimpleXMLElement 在一行中获取第一个 XPath 元素 [英] SimpleXMLElement get first XPath Element in one line

查看:35
本文介绍了SimpleXMLElement 在一行中获取第一个 XPath 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想找出一种更短的方法来做到这一点:

Just trying to figure a shorter way to do this:

我正在使用 simpleXMLElement 来解析一个 xml 文件,当我知道我想要什么节点时,不得不调用两行来处理一个数组,这很麻烦.

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.

当前代码:

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

我想做的事情就像我可以用 DomX 做的一样

What I would like to do would be something like I can do with DomX

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

推荐答案

在 PHP

5.4(支持对函数或方法调用的结果进行数组解引用)您可以在 列表:

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');

从 PHP 5.4 开始,它更直接:

Since PHP 5.4 it's more straight forward with:

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

请注意,如果 xpath 方法返回至少包含一个元素的数组,则这些仅在没有任何通知的情况下起作用.如果您对此不确定并且需要一个默认值,则可以使用数组联合运算符来实现.

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.

在 PHP <5.4 默认返回值为 NULL 的代码为:

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);

对于 PHP 5.4+ 来说是类似的,这里的一个好处是新的数组语法只带方括号:

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];

<小时>

另见:

注意: 因为你只需要一个元素,你不应该已经通过 xpath 返回多个元素:

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];
                                               ###

这篇关于SimpleXMLElement 在一行中获取第一个 XPath 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆