Remove empty tags from a XML with PHP

前端 未结 5 1141
悲哀的现实
悲哀的现实 2020-11-27 08:02

Question

How can I remove empty xml tags in PHP?

Example:

 $value1 = \"2\";
 $value2 = \"4\";
 $value3 = \"\";

 xml = \'

        
5条回答
  •  爱一瞬间的悲伤
    2020-11-27 08:21

    The solution that worked with my production PHP SimpleXMLElement object code, by using Xpath, was:

    /*
     * Remove empty (no children) and blank (no text) XML element nodes, but not an empty root element (/child::*).
     * This does not work recursively; meaning after empty child elements are removed, parents are not reexamined.
     */
    foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
        unset( $emptyElement[0] );
    }
    

    Note that it is not required to use PHP DOM, DOMDocument, DOMXPath, or dom_import_simplexml().

    //this is a recursively option
    
    do {
        $removed = false;
        foreach( $this->xml->xpath('/child::*//*[not(*) and not(text()[normalize-space()])]') as $emptyElement ) {
            unset( $emptyElement[0] );
            $removed = true;
        }
    } while ($removed) ;
    

提交回复
热议问题