Zend - The PHP Company




XML

Add Code


xml_formatter  

Type: code fragment
Added by: shmert
Entered: 14/03/2002
Last modified: 03/12/2001
Rating: - (fewer than 3 votes)
Views: 4605
Adds indents and line breaks to an XML document, making for much easier viewing.


<?php
function xml_format($xml) {
    
$xml str_replace ("n"""$xml);
    
$xml str_replace ("r"""$xml);
    
$out preg_replace_callback("|<[^>]*>[^<]*|""_xml_format_element"$xml);
    
$out str_replace ('<''&lt;'$out);
    
$out str_replace ('>''&gt;'$out);
    return 
nl2br($out);
}

function 
_xml_format_element($array) {
    
// callback function for xml_format.  Do not invoke directly //
    
$found $array[0];
    static 
$indent;
    
$found trim($found);
    
$tagOffset 1;
    
$openingText "n";
    
$tab str_repeat("&nbsp;"$indent 4);
    if (
substr($found02)=='</') {
        
// closing tag //
        
$tagOffset 2;
        
$indent--;
        
$tab str_repeat("&nbsp;"$indent *4);
    } else if (
substr($found, -21)=='/' || strpos($found'/>')) {
        
// opening and closing tag //
        // do not change indent //
    
} else {
        
// opening tag //
        
$indent++;
    }
    
// $content = substr(strrchr($found, '>'), 0, -1);
    
if (substr($found, -1) != '>') {
        
// indent the content //
        
$found str_replace (">"">n" str_repeat("&nbsp;", ($indent+0)*4), $found);
    }
    return 
$openingText $tab $found ;
}
?>


Usage Example


$xml = join ("", file("sample.xml"));
echo xml_format($xml);


Rate This Script





Search



This Category All Categories