php SimpleXML check if a child exists

2019-01-04 02:53发布

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

标签: php simplexml
15条回答
▲ chillily
2楼-- · 2019-01-04 03:13

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

查看更多
闹够了就滚
3楼-- · 2019-01-04 03:14

I use a helper function to check if a node is a valid node provided as a parameter in function.

private static function isValidNode($node) {
  return isset($node) && $node instanceof SimpleXMLElement && !empty($node);
}

Usage example:

public function getIdFromNode($node) {
  if (!self::isValidNode($node)) {
    return 0;
  }
  return (int)$node['id'];
}
查看更多
在下西门庆
4楼-- · 2019-01-04 03:17

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 
}
查看更多
看我几分像从前
5楼-- · 2019-01-04 03:18

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

if( !empty($a->b)){
  var_dump($a->b);
}
查看更多
ら.Afraid
6楼-- · 2019-01-04 03:19

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
}
查看更多
Melony?
7楼-- · 2019-01-04 03:20

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.

查看更多
登录 后发表回答