1

In the below code I'm trying to access @attributes of Userinfo as $somevariable->Userinfo->attributes(); which is perfectly fine, but when there is no @attributes it throws an error

Call to a member function attributes() on null

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

)

So, before accessing @attributes, how to check if it exist ?

Thank you.

2
  • 1
    Can you show the XML(and not the array version) and the actual code your using. The error seems to indicate the Userinfo is not there rather than the attributes missing. Commented Oct 23, 2018 at 5:38
  • Yes @Nigel Ren this was the issue, actually Userinfo I'm getting from api dynamically, for some case it was not received I guess. Commented Oct 23, 2018 at 6:10

1 Answer 1

1

You can use !empty()

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

Sample output:- https://3v4l.org/R32Bv

Or you can use isset() too

if(isset($somevariable->Userinfo)){
  // do stuff here
}
Sign up to request clarification or add additional context in comments.

2 Comments

In your code I made some changes and found that it is enough to to check if $somevariable->Userinfo exist, however your code also works :).. thanks
@KArunSingh glad to help you :):)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.