php SimpleXML check if a child exists

后端 未结 16 1931
粉色の甜心
粉色の甜心 2020-11-27 06:24

A->b->c might exist but c might not exist. How do I check it?

相关标签:
16条回答
  • 2020-11-27 06:58

    If you have PHP 5.3, you can just use $a->count(). Otherwise, scippie's solution using @count($a->children()) works well. I find I don't need the @ but older PHP implementations may need it.

    0 讨论(0)
  • 2020-11-27 06:58

    The 3 ways I can confirm work in PHP 5.5.23 were using isset() count() or empty()

    Here is a script to show the results from each:

    https://gist.github.com/mchelen/306f4f31f21c02cb0c24

    0 讨论(0)
  • 2020-11-27 06:59

    It might be better to wrap this in an isset()

    if(isset($A->b->c)) { // c exists
    

    That way if $A or $A->b don't exist... it doesn't blow up.

    0 讨论(0)
  • 2020-11-27 06:59

    Using if(isset($A->b){ gave me issues, so I tried if($A->b){ and it worked!

    0 讨论(0)
  • Thought I'd share my experience. Running on 5.4 I tried testing with 'isset' and 'empty' but neither worked for me. I ended up using is_null.

    if(!is_null($xml->scheduler->outterList->innerList)) {
        //do something
    }
    
    0 讨论(0)
  • 2020-11-27 07:04

    SimpleXML always return Object. If there is no child, empty object is returned.

    if( !empty($a->b)){
      var_dump($a->b);
    }
    
    0 讨论(0)
提交回复
热议问题