PHP “pretty print” HTML (not Tidy)

后端 未结 3 454
耶瑟儿~
耶瑟儿~ 2020-11-29 04:53

I\'m using the DOM extension in PHP to build some HTML documents, and I want the output to be formatted nicely (with new lines and indentation) so that it\'s readable, howev

3条回答
  •  感情败类
    2020-11-29 05:11

    you're right, there seems to be no indentation for HTML (others are also confused). XML works, even with loaded code.

    preserveWhiteSpace = false;
        $dom->loadHTML($buffer);
        $dom->formatOutput = true;
        return($dom->saveHTML());
    }
    
    // start output buffering, using our nice
    // callback function to format the output.
    ob_start("tidyHTML");
    
    ?>
    
        
        foo bar

    bar foo

    It's like comparing apples to oranges.

    result:

    
    
    
    foo bar
    
    
    
    

    bar foo

    It's like comparing apples to oranges.

    the same with saveXML() ...

    
    
    
      
        foo bar
        
      
      
        

    bar foo

    It's like comparing apples to oranges.

    probably forgot to set preserveWhiteSpace=false before loadHTML?

    disclaimer: i stole most of the demo code from tyson clugg/php manual comments. lazy me.


    UPDATE: i now remember some years ago i tried the same thing and ran into the same problem. i fixed this by applying a dirty workaround (wasn't performance critical): i just somehow converted around between SimpleXML and DOM until the problem vanished. i suppose the conversion got rid of those nodes. maybe load with dom, import with simplexml_import_dom, then output the string, parse this with DOM again and then printed it pretty. as far as i remember this worked (but it was really slow).

提交回复
热议问题