2012-06-06 55 views
6

我有我使用PHP的SimpleXML类的一些XML和我在XML中的元素,如:检查,如果一个对象的属性设置 - SimpleXML的

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

但是他们并不总是存在,所以我需要检查它们是否先存在。

我已经试过..

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

以及..

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

但无论工作。他们只在删除属性部分时才起作用。

那么如何检查一个属性是否被设置为对象的一部分呢?

回答

12

什么你看是属性值。你需要看看(在这种情况下name)的属性本身:

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

好一点 - 感谢! – Brett

6

其实,你真的应该使用SimpleXMLElement::attributes(),但你应该检查对象之后使用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 
} 
相关问题