Object Attribute Verification - SimpleXML

I have some XML. I use the PHP SimpleXML class, and I have elements in XML, such as:

<condition id="1" name="New"></condition> <condition id="2" name="Used"></condition> 

However, they do not always exist, so I need to check if they exist in the first place.

I tried..

 if (is_object($bookInfo->page->offers->condition['used'])) { echo 'yes'; } 

and..

 if (isset($bookInfo->page->offers->condition['used'])) { echo 'yes'; } 

But no one is working. They only work if I delete the attribute part.

So how can I check if an attribute is set as part of an object?

+6
source share
3 answers

What you are looking for is the value of the attribute. You need to look at the attribute ( name in this case):

 if (isset($bookInfo->page->offers->condition['name']) && $bookInfo->page->offers->condition['name'] == 'Used') //-- the rest is up to you 
+12
source

Actually, you really should use SimpleXMLElement :: attributes () , but after that you should check the object using isset () :

 $attr = $bookInfo->page->offers->condition->attributes(); if (isset($attr['name'])) { //your attribute is contained, no matter if empty or with a value } else { //this key does not exist in your attributes list } 
+6
source

You can use SimpleXMLElement :: attributes ()

 $attr = $bookInfo->page->offers->condition->attributes(); if ($attr['name'] == 'Used') { // ... 
+1
source

Source: https://habr.com/ru/post/917426/


All Articles