reg*_*gie 11 php xml exists simplexml
我有这个simplexml结果对象:
object(SimpleXMLElement)#207 (2) {
["@attributes"]=>
array(1) {
["version"]=>
string(1) "1"
}
["weather"]=>
object(SimpleXMLElement)#206 (2) {
["@attributes"]=>
array(1) {
["section"]=>
string(1) "0"
}
["problem_cause"]=>
object(SimpleXMLElement)#94 (1) {
["@attributes"]=>
array(1) {
["data"]=>
string(0) ""
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要检查节点"problem_cause"是否存在.即使它是空的,结果也是错误的.在php手册上,我找到了我为我的需求修改的PHP代码:
function xml_child_exists($xml, $childpath)
{
$result = $xml->xpath($childpath);
if (count($result)) {
return true;
} else {
return false;
}
}
if(xml_child_exists($xml, 'THE_PATH')) //error
{
return false;
}
return $xml;
Run Code Online (Sandbox Code Playgroud)
我不知道用什么代替xpath查询'THE_PATH'来检查节点是否存在.或者将simplexml对象转换为dom更好吗?
Vol*_*erK 35
听起来像一个简单的isset()解决了这个问题.
<?php
$s = new SimpleXMLElement('<foo version="1">
<weather section="0" />
<problem_cause data="" />
</foo>');
// var_dump($s) produces the same output as in the question, except for the object id numbers.
echo isset($s->problem_cause) ? '+' : '-';
$s = new SimpleXMLElement('<foo version="1">
<weather section="0" />
</foo>');
echo isset($s->problem_cause) ? '+' : '-';
Run Code Online (Sandbox Code Playgroud)
打印时+-没有任何错误/警告消息.