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条回答
对你真心纯属浪费
2楼-- · 2019-01-04 03:38
if($A->b->c != null) //c exists

If c does not exist, its value will be null (or, to be more precise, it will have no value). Note, however, that for this to work, both A and b need to not be null. Otherwise, PHP will throw an error (I think).

查看更多
疯言疯语
3楼-- · 2019-01-04 03:39

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

查看更多
在下西门庆
4楼-- · 2019-01-04 03:40

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

查看更多
登录 后发表回答