检查是否设置了对象属性 - 简单 XML


Checking if an object attribute is set - SimpleXML

我有一些XML,我正在使用PHP的SimpleXML类,我在XML中有元素,例如:

<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';
}

但两者都不起作用。它们仅在我删除属性部分时才有效。

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

您正在查看的是属性值。您需要查看属性(在本例中为name)本身:

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

实际上,你应该真正使用 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
}

您可以使用 SimpleXMLElement::attributes()

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