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条回答
Emotional °昔
2楼-- · 2019-01-04 03:21

You could try:

if($A->b->c && $A->b->c != '')
查看更多
Animai°情兽
3楼-- · 2019-01-04 03:23

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

查看更多
小情绪 Triste *
4楼-- · 2019-01-04 03:30

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.

查看更多
来,给爷笑一个
5楼-- · 2019-01-04 03:36

Using xpath:

function has_child(\SimpleXMLElement $parent=null, string $xpathToChild)
{
    return isset($parent) && !empty($parent->xpath('('.$xpathToChild.')[1]'));
}

where $parent is an indirect or direct parent of the child node to check and $xpathToChild is an xpath of the child relative to $parent.

()[1] is because we don't want to select all the child nodes. One is enough.

To check if $a->b->c exists:

has_child($a,'b/c');

You can also check for attributes. To check if the node c has the t attribute.

has_child($a,'b/c/@t');
查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-04 03:37

Method xpath returns array of matched elements or false

if(false !== $A->xpath('b/c')) { ...

http://www.php.net/manual/ru/simplexmlelement.xpath.php

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-04 03:37

Simply

var_dump(count($xml->node));
查看更多
登录 后发表回答