Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查PHP中是否存在xml节点_Php_Xml_Simplexml_Exists - Fatal编程技术网

检查PHP中是否存在xml节点

检查PHP中是否存在xml节点,php,xml,simplexml,exists,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"]=> s

我有一个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) ""
   }
  }
  }
 }
我需要检查节点“问题原因”是否存在。即使它是空的,结果也是错误的。 在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更好?

Put
*/problem\u因为

听起来很简单,可以解决这个问题

<?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)  ? '+' : '-';
问题原因?“+”:“-”; $s=新的SimpleXMLElement(' '); echo isset($s->问题原因)?“+”:“-”;
打印
+-
时不显示任何错误/警告消息。

使用您发布的代码,此示例可以在任何深度查找问题原因节点

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';
}
试试这个:

 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';
     }
 }

我希望这对你有帮助。

哦,谢谢。这是一个非常简单的解决方案。最好使用
empty()
而不是
isset()
。如果对象的子对象不存在,则访问该子对象将创建它,因此SimpleXMLElement将返回一个空元素,
isset()
将返回true。@MugomaJ.Okomba
empty()
即使节点存在但没有内容也返回true