How to tell apart SimpleXML objects representing element and attribute?

后端 未结 6 1018
猫巷女王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:58

    Is there a hidden property/method that allows identifying type of node in SimpleXML? Equivalent of DOM's $node->nodeType or $node instanceof DOMAttr? (I can't use DOM instead, support for SimpleXML is core requirement)

    The answer is no... and yes. SimpleXML doesn't have such a property but here's the good news: SimpleXML and DOM are two faces of the same coin. (the coin is libxml ;)) You don't have to choose one or the other, you can use both! You can turn SimpleXMLElement into DOMNode and vice versa. In your case, you could do something like:

    $element = new SimpleXMLElement('');
    $is_attr = (dom_import_simplexml($element['attr'])->nodeType === XML_ATTRIBUTE_NODE);
    

    If that's something you do often, or you don't want to handle the DOM/SimpleXML juggling, you can take a look at SimpleDOM.

    $element = new SimpleDOM('');
    $is_attr = ($element['attr']->nodeType() === XML_ATTRIBUTE_NODE);
    

提交回复
热议问题