检查PHP中是否存在xml节点

时间:2010-09-05 13:12:28

标签: php xml simplexml exists

我有这个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) ""
   }
  }
  }
 }

我需要检查节点“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更好吗?

4 个答案:

答案 0 :(得分:34)

听起来很简单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)  ? '+' : '-';

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

答案 1 :(得分: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';
}

答案 2 :(得分: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';
     }
 }

我希望这会对你有帮助..

答案 3 :(得分:0)

*/problem_cause

相关问题