php SimpleXML check if a child exists

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

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

相关标签:
16条回答
  • 2020-11-27 07:05

    After some experimentation, I've discovered that the only reliable method of checking if a node exists is using count($xml->someNode).

    Here's a test case: https://gist.github.com/Thinkscape/6262156

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

    Name Spaces

    Be aware that if you are using name spaces in your XML file you will need to include those in your function calls when checking for children otherwise it will return ZERO every time:

    if ($XMLelement->children($nameSpace,TRUE)->count()){
        //do something here 
    }
    
    0 讨论(0)
  • 2020-11-27 07:09

    I solved it by using the children() function and doing a count() on it, ignoring an PHP error if there are no children by putting an @ before the count-call. This is stupid, but it works:

    $identification = $xml->identification;
    if (@count($identification->children()) == 0)
      $identification = $xml->Identification;
    

    I hate this...

    0 讨论(0)
  • 2020-11-27 07:14

    Simply

    var_dump(count($xml->node));
    
    0 讨论(0)
提交回复
热议问题