Bre*_*ett 7 php xml object simplexml
我有一些XML我正在使用PHP的SimpleXML类,我在XML中有如下元素:
<condition id="1" name="New"></condition>
<condition id="2" name="Used"></condition>
Run Code Online (Sandbox Code Playgroud)
但是它们并不总是存在,所以我需要先检查它们是否存在.
我试过了..
if (is_object($bookInfo->page->offers->condition['used'])) {
echo 'yes';
}
Run Code Online (Sandbox Code Playgroud)
以及..
if (isset($bookInfo->page->offers->condition['used'])) {
echo 'yes';
}
Run Code Online (Sandbox Code Playgroud)
但是没有工作.它们仅在我删除属性部分时才起作用.
那么如何检查属性是否设置为对象的一部分?
ses*_*ser 13
您正在查看的是属性值.您需要查看属性(name在本例中)本身:
if (isset($bookInfo->page->offers->condition['name']) && $bookInfo->page->offers->condition['name'] == 'Used')
//-- the rest is up to you
Run Code Online (Sandbox Code Playgroud)
实际上,你应该使用SimpleXMLElement :: attributes(),但是你应该使用isset()检查Object :
$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
}
Run Code Online (Sandbox Code Playgroud)