Beautify [Format] XML with PHP
There is a myriad of XML formating tools out there, some have reached a rather stable development state. Oddly enough, an XML file having elements with both content and child elements is all it takes for most of them them [every single one i know of] to miserably fail. Being that a basic XML feature, I decided to give it a go.
It was pretty straight forward…
function beautify($xmlString){
$outputString = "";
$previousBitIsCloseTag = false;
$indentLevel = 0;
$bits = explode("<", $xmlString);
foreach($bits as $bit){
$bit = trim($bit);
if (!empty($bit)){
if ($bit[0]=="/"){ $isCloseTag = true; }
else{ $isCloseTag = false; }
if(strstr($bit, "/>")){
$prefix = "\n".str_repeat(" ",$indentLevel);
$previousBitIsSimplifiedTag = true;
}
else{
if ( !$previousBitIsCloseTag and $isCloseTag){
if ($previousBitIsSimplifiedTag){
$indentLevel--;
$prefix = "\n".str_repeat(" ",$indentLevel);
}
else{
$prefix = "";
$indentLevel--;
}
}
if ( $previousBitIsCloseTag and !$isCloseTag){$prefix = "\n".str_repeat(" ",$indentLevel); $indentLevel++;}
if ( $previousBitIsCloseTag and $isCloseTag){$indentLevel--;$prefix = "\n".str_repeat(" ",$indentLevel);}
if ( !$previousBitIsCloseTag and !$isCloseTag){{$prefix = "\n".str_repeat(" ",$indentLevel); $indentLevel++;}}
$previousBitIsSimplifiedTag = false;
}
$outputString .= $prefix."<".$bit;
$previousBitIsCloseTag = $isCloseTag;
}
}
return $outputString;
}
Note:
I totally forgot CDATA handling. Maybe that's a good subject to some other post. Maybe, if I happen to need that feature.
Tags: php, programming, XML