php - 检查PHP中是否存在xml节点

标签 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 更好?

最佳答案

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

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

关于php - 检查PHP中是否存在xml节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3646153/

相关文章:

php - 对学说的@OneToMany ArrayCollection 进行排序

php - 从 HTML 中删除 img 和 p 标签

java - 我可以使用 jsoup 进行 html 到 xml 的转换吗?

python - 将 xml 转换为 python 字典

c# - 反序列化具有不同 XmlRoot 元素名称的 XML 文件

php - SimpleXMLElement-> xpath()显示不在对象中的数据

php - MySQL关系数据库设计

php - 嵌套的 foreach 循环,使用 php 和 laravel

php - simplexml_load_file结果为空页

php - 如何使用 SimpleXML 检查元素是否存在?