How to tell apart SimpleXML objects representing element and attribute?

后端 未结 6 1016
猫巷女王i
猫巷女王i 2020-12-04 00:30

I need to print arbitrary SimpleXML objects in a specific manner, with special handling of attribute nodes.

The problem is that SimpleXML elements and attri

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 00:57

    Unfortunately there is no hidden property or method that allows identifying the type of node in SimpleXML. SimpleXML only uses one Class and elements do not have anything that point to their parents. If you try the below reflection you will see that there is nothing to distinguish element or attribute.

    $element = new SimpleXMLElement('test');
    echo ReflectionObject::export($element);
    
    $element = new SimpleXMLElement('test');
    echo ReflectionObject::export($element['attr']);
    

    However if an element has attributes you can detect that. So you would have to assume that all elements passed in have attributes. With that assumption you could tell them apart.

    $element = new SimpleXMLElement('test');
    
    echo ReflectionObject::export($element);
    echo ReflectionObject::export($element['attr']);
    

    This is the best I can come up with. Remember it's possible for an element with no attributes to still return false with this.

    function isNotAttribute($simpleXML)
    {
      return (count($simpleXML->attributes()) > 0);
    }
    
    $element = new SimpleXMLElement('test');
    var_dump(isNotAttribute($element));
    var_dump(isNotAttribute($element['attr']));
    
    // returns
    bool(true)
    bool(false)
    

提交回复
热议问题