12

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) ""
   }
  }
  }
 }

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;

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?

codaddict
  • 445,704
  • 82
  • 492
  • 529
reggie
  • 3,523
  • 14
  • 62
  • 97

4 Answers4

37

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.

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • 1
    Oh, thanks. That is a very easy solution. – reggie Sep 07 '10 at 08:42
  • It's better to use `empty()` than `isset()`. Accessing a child of the object will create it if it does not exist, so SimpleXMLElement will return an empty element and `isset()` will return true. – Mugoma J. Okomba Mar 26 '17 at 13:49
  • @MugomaJ.Okomba `empty()` returns true even if the node exists but has no contents – CITBL Apr 18 '17 at 11:46
3

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';
}
Chris Gutierrez
  • 4,750
  • 19
  • 18
1

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..

Weles
  • 1,275
  • 13
  • 17
AliMohsin
  • 329
  • 1
  • 5
  • 10
0

Put */problem_cause.

aularon
  • 11,042
  • 3
  • 36
  • 41