存在XML节点我有这个SimpleXML的结果对象:检查是否在PHP
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) ""
}
}
}
}
我需要检查,如果节点“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;
我不知道该怎么落实到位XPath查询“THE_PATH”的检查,如果节点存在。 或者将simplexml对象转换为dom更好吗?
哦,谢谢。这是一个非常简单的解决方案。 – reggie 2010-09-07 08:42:09
最好使用'empty()'而不是'isset()'。如果访问对象的子对象不存在,它将创建它,所以SimpleXMLElement将返回一个空元素,并且'isset()'将返回true。 – 2017-03-26 13:49:31
@ MugomaJ.Okomba'empty()'返回true,即使节点存在但没有内容 – CITBL 2017-04-18 11:46:44