Brett
Brett

Reputation: 20049

Checking if an object attribute is set - SimpleXML

I have some XML I am using PHP's SimpleXML class with and I have elements within the XML such as:

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

However they are not always there, so I need to check if they exist first.

I have tried..

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

as well as..

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

But neither work. They only work if I remove the attribute part.

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

Upvotes: 9

Views: 20893

Answers (3)

Florian M&#252;ller
Florian M&#252;ller

Reputation: 7785

Actually, you should really use SimpleXMLElement::attributes(), but you should check the Object afterwards 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
}

Upvotes: 8

sesser
sesser

Reputation: 1165

What you're looking at is the attribute value. You need to look at the attribute (name in this case) itself:

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

Upvotes: 14

dan-lee
dan-lee

Reputation: 14502

You can use SimpleXMLElement::attributes()

$attr = $bookInfo->page->offers->condition->attributes();

if ($attr['name'] == 'Used') {
  // ...

Upvotes: 1

Related Questions