Generate indented XML through PHP

2

Hello, good morning.

I am generating xml with php, but the code is getting everything in a single line, I need it to be indented when it is generated, respecting the hierarchy. I have no idea how to do this

Follow the code used

<?php
if(isset($_POST['create_xml'])){ echo "Programação das salas realizada";
/* All Links data from the form is now being stored in variables in string format */
$miro = $_POST['miro'];
$monet = $_POST['monet'];
$picasso = $_POST['picasso'];
$xmlBeg = "<?xml version='1.0' encoding='utf-8'?>";
$rootELementStart = "<reunioes>";
$rootElementEnd = "</reunioes>";
$xml_document= $xmlBeg;
$xml_document .= $rootELementStart;
$xml_document .= "<monet>";
$xml_document .= $monet; $xml_document .= "</monet>";
$xml_document .= "<picasso>";
$xml_document .= $picasso; $xml_document .= "</picasso>";
$xml_document .= "<miro>";
$xml_document .= $miro; $xml_document .= "</miro>"; 
$xml_document .= $rootElementEnd; 
$path_dir .= "reunioes" .".xml"; 

/* Data in Variables ready to be written to an XML file */ 
$fp = fopen($path_dir,'w'); 
$write = fwrite($fp,$xml_document); 
/* Loading the created XML file to check contents */ 
$sites = simplexml_load_file("$path_dir"); 
echo "<br> Checking the loaded file <br>" .$path_dir. "<br>"; 
?>

link

    
asked by anonymous 11.07.2016 / 16:26

1 answer

4

Manually Generated XML

I do not quite understand the difficulty, since you are the one who is generating the XML "manually". Basically, applying this logic across all lines would suffice:

$xml_document .= "\t\t\t<monet>\n";
  • Each \t is a tab , enter the right amount for each level of indentation

  • The \n is the line break.

See working at IDEONE .


General solution with DOM

Now, if you need to format an XML already ready, you can use the DOM .

$xml = '<root><foo><bar>baz</bar></foo></root>';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$dom->formatOutput = TRUE;
$formatado = $dom->saveXml();

echo $formatado;

Result:

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

See working at IDEONE .

    
11.07.2016 / 16:31