本文介绍了检查PHP中是否存在xml节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个simplexml结果对象:
I have this simplexml result object:
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代码:
I need to check if the node "problem_cause" exists. Even if it is empty, the result is an error.On the php manual, I found this php code that I modified for my needs:
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更好?
I have no idea what to put in place of the xpath query 'THE_PATH' to check if the node exists.Or is it better to convert the simplexml object to dom?
推荐答案
听起来像一个简单的 isset()解决了这个问题.
Sounds like a simple isset() solves this problem.
<?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) ? '+' : '-';
打印+-
,没有任何错误/警告消息.
prints +-
without any error/warning message.
这篇关于检查PHP中是否存在xml节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!