2010-09-05 75 views
7

存在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更好吗?

回答

27

听起来像一个简单的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) ? '+' : '-'; 

打印+-没有任何错误/警告消息。

+0

哦,谢谢。这是一个非常简单的解决方案。 – reggie 2010-09-07 08:42:09

+0

最好使用'empty()'而不是'isset()'。如果访问对象的子对象不存在,它将创建它,所以SimpleXMLElement将返回一个空元素,并且'isset()'将返回true。 – 2017-03-26 13:49:31

+0

@ MugomaJ.Okomba'empty()'返回true,即使节点存在但没有内容 – CITBL 2017-04-18 11:46:44

2

使用您发布的代码,本示例应该可以在任意深度查找problem_cause节点。

function xml_child_exists($xml, $childpath) 
{ 
    $result = $xml->xpath($childpath); 
    return (bool) (count($result)); 
} 

if(xml_child_exists($xml, '//problem_cause')) 
{ 
    echo 'found'; 
} 
else 
{ 
    echo 'not found'; 
} 
1

试试这个:

function xml_child_exists($xml, $childpath) 
{ 
    $result = $xml->xpath($childpath); 
    if(!empty($result)) 
{ 
    echo 'the node is available'; 
} 
else 
{ 
    echo 'the node is not available'; 
} 
} 

我希望这将帮助你..