【问题标题】:How to check if SimpleXMLElement Object's attribute exist - PHP如何检查 SimpleXMLElement 对象的属性是否存在 - PHP
【发布时间】:2019-03-27 06:03:29
【问题描述】:

在下面的代码中,我试图以$somevariable->Userinfo->attributes(); 访问@attributesUserinfo,这很好,但是当没有@attributes 时,它会引发错误

在 null 上调用成员函数 attributes()

[Userinfo] => SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [UserId] => 121
            [UserName] => Arun, Singh
            [UserEmail] => abc@xyz.com
            [CreatedDate] => 06/27/2018 08:44:21
        )

)

那么,在访问@attributes之前,如何检查它是否存在?

谢谢。

【问题讨论】:

  • 您能否显示 XML(而不是数组版本)和您使用的实际代码。该错误似乎表明Userinfo 不存在,而不是缺少属性。
  • 是的@Nigel Ren,这就是问题所在,实际上Userinfo我是动态从api获取的,在某些情况下我猜它没有收到。

标签: php xml properties simplexml


【解决方案1】:

你可以使用!empty()

if(!empty($somevariable->Userinfo->attributes())){
  // do stuff here
}

示例输出:- https://3v4l.org/R32Bv

或者你也可以使用isset()

if(isset($somevariable->Userinfo)){
  // do stuff here
}

【讨论】:

  • 在您的代码中我做了一些更改,发现检查$somevariable->Userinfo 是否存在就足够了,但是您的代码也可以工作:).. 谢谢
  • @KArunSingh 很高兴为您提供帮助:):)
猜你喜欢
  • 2013-01-03
  • 2013-10-20
  • 2020-06-20
  • 1970-01-01
  • 2021-10-08
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多