Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format xml string

Tags:

string

php

xml

What is the best way to format XML within a PHP class.

$xml = "<element attribute=\"something\">...</element>";  $xml = '<element attribute="something">...</element>';  $xml = '<element attribute=\'something\'>...</element>';  $xml = <<<EOF <element attribute="something"> </element> EOF; 

I'm pretty sure it is the last one!

like image 695
quj Avatar asked Sep 01 '10 09:09

quj


People also ask

How do you format XML?

To access XML formatting options, choose Tools > Options > Text Editor > XML, and then choose Formatting.

Can we format XML in Notepad ++?

Notepad++ has support for validation of XML file content. Validation can be done using Plugin Menu -> XML Tools ->Validate option or you can use short cut CTRL+ALT+Shift+M.


2 Answers

With DOM you can do

$dom = new DOMDocument; $dom->preserveWhiteSpace = FALSE; $dom->loadXML('<root><foo><bar>baz</bar></foo></root>'); $dom->formatOutput = TRUE; echo $dom->saveXML(); 

gives (live demo)

<?xml version="1.0"?> <root>   <foo>     <bar>baz</bar>   </foo> </root> 

See DOMDocument::formatOutput and DOMDocument::preserveWhiteSpace properties description.

like image 185
Gordon Avatar answered Oct 07 '22 14:10

Gordon


This function works perfectlly as you want you don't have to use any xml dom library or nething just pass the xml generated string into it and it will parse and generate the new one with tabs and line breaks.

function formatXmlString($xml){     $xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml);     $token      = strtok($xml, "\n");     $result     = '';     $pad        = 0;      $matches    = array();     while ($token !== false) :          if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) :            $indent=0;         elseif (preg_match('/^<\/\w/', $token, $matches)) :           $pad--;           $indent = 0;         elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) :           $indent=1;         else :           $indent = 0;          endif;         $line    = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT);         $result .= $line . "\n";         $token   = strtok("\n");         $pad    += $indent;     endwhile;      return $result; } 
like image 22
pravat231 Avatar answered Oct 07 '22 14:10

pravat231