php 检查PHP中是否存在xml节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3646153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if xml node exists in PHP
提问by reggie
I have this simplexml result object:
我有这个 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) ""
}
}
}
}
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:
我需要检查节点“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;
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?
我不知道用什么代替 xpath 查询“THE_PATH”来检查节点是否存在。还是将 simplexml 对象转换为 dom 更好?
回答by VolkerK
Sounds like a simple isset()solves this problem.
听起来像一个简单的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) ? '+' : '-';
prints +-without any error/warning message.
打印时+-没有任何错误/警告消息。
回答by Chris Gutierrez
Using the code you had posted, This example should work to find the problem_cause node at any depth.
使用您发布的代码,此示例应该可以在任何深度找到 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';
}
回答by AliMohsin
try this:
尝试这个:
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';
}
}
i hope this will help you..
我希望这能帮到您..
回答by aularon
Put */problem_cause.
放*/problem_cause。

