Check if xml node exists in PHP
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.
Using the code you had posted, This example should work to find the problem_cause node at any depth.
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';
}