Jump to content

Recommended Posts

I have created this short function for formatting xml strings using recursion and anonymous function. Can you guys check and tell me if it is really working...?

 

Also if this can be done in a shorter way?

 

Please avoid the xml version tags and the style sheet declarations for now, as it would break the function. I have included a sample xml in the code posted below...

 

<?php 
$xmlstr = <<<EOB
<Item xmlns="http://uriofthenamespace.com" Type="Book"><Name>Freedom at Midnight</Name><Authors><Author><FirstName>Collins</FirstName><LastName>Larry</LastName></Author><Author><FirstName>Lapierre</FirstName><LastName>Dominique</LastName></Author></Authors><Price><![CDATA[150.00]]></Price></Item>
EOB;
function indent($str,$il=0,&$count=null)
{
$indentChar = "  ";
$str = preg_replace("#>\s*(\w|<)#",">\\1",$str);
$replacer = function($str) use($il,$indentChar)
{
$str[3] = trim($str[3]);
$count = 0;
if(substr($str[3],0,9)!='<![CDATA[') $str[3] = indent($str[3],$il+1,$count);
$n=$count?"":"\n$indentChar";
$str[3] = str_replace("\n","\n".str_repeat($indentChar,$il),$str[3]);
return "\n{$str[1]}$n{$str[3]}\n</{$str[2]}>";
};
$return = preg_replace_callback("#(<(\w*?).*>)(.*)</\\2>#Uism",$replacer,$str,-1,$count);
if($il==0) 
return preg_replace("#(<\w*/>)([^<]+)\n(\s*)<#Uism","\\1\n\\3$indentChar\\2\\3\n\\3<",preg_replace("#(<\w*/>)\n(\s*)(\S)#Uism","\n$indentChar\\2\\1\n\\2\\3",$return));
else 
return $return;
}

echo indent($xmlstr);

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.