How to tell apart SimpleXML objects representing element and attribute?

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

    Yes there is a way. Well, nothing elegant that you can retrieve via the API, but somewhere in the guts of the SimpleXML is keeping track of what it is and it makes a differences, for example, when you call functions such as getName() or asXML().

    $element = new SimpleXMLElement('test');
    print_r($element->getName());
    print_r($element->asXML());
    echo "------------------\n";
    $element = new SimpleXMLElement('');
    $at = $element['attr'];
    print_r($at->getName());
    print_r($at->asXML());
    
    foo
    
    test
    ------------------
    attr 
    attr="test"
    

    Your code won't win a beauty contest, but at least you can do it.

提交回复
热议问题