How to tell apart SimpleXML objects representing element and attribute?

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

    You need SimpleXMLElement::attributes:

    function xml_out($el) {
        $name = $el->getName();
        echo '<'. $name;
    
        if (count($el->attributes())) {
            foreach ($el->attributes() as $a=>$v) {
                echo ' '. ((string)$a) . '="' . htmlspecialchars((string)$v) . '"';
            }
        }
    
        echo '>'. (string)$el;
    
        if (count($el->children())) {
            foreach($el->children() as $c) {
                xml_out($c);
            }
        }
        echo '';
    
    }
    

    May need a bit of tweaking.

提交回复
热议问题