当循环遍历下面的xml对象时,我需要从每个属性中获取数据,如果属性不存在,请继续。我不知道如何检查@attributes是否存在。目前,如果它没有我的循环死亡。
我试过了:
if(isset($v[0]->user->attributes())){
....
but that gives me a php error:
Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
所以我不确定如何检查它是否存在,如果它存在,我可以通过循环。如果它不能继续......
[server] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 17980
)
[user] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 1075159
[default-loc] => 50000
[status] => 1
[license] => high,standard
[password] => aebecf880f2060c31e44f820785e0aa63ea4cc44
[primary] => 50000
[username] => 17980_50000
)
[description] => Customer X
)
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 14642
)
[user] => Array
(
[0] => SimpleXMLElement Object
(
[description] => Customer Y
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 24151
)
[user] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 1075159
[default-loc] => 50000
[status] => 1
[license] => high,low
[password] => aebecf880f2060c31e44f820785e0aa63ea4cc44
[primary] => 51412
[username] => 17980_51412
)
[description] => Customer Z
)
)
)
)
答案 0 :(得分:0)
我不确定这会对您有多大帮助,但是在尝试迭代XML时。我发现最好使用递归而不是循环。您的问题没有显示您是使用递归函数还是循环,但您确实说“循环时...”
如果以递归方式解决此问题,只要检测到您位于属性类型的叶节点,就可以停止并执行所需的操作。
这应该消除在简单地“循环”XML时可能遇到的任何潜在的空指针异常。
答案 1 :(得分:0)
if(isset($v[0]->user->attributes())){
在这一行上,attributes()返回一个属性数组,所以你实际上想要说一些像......
if(count($v[0]->user->attributes()))>0){