Generate indented XML via PHP

Asked

Viewed 553 times

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 ideated when generated, respecting the hierarchy. I have no idea how you do it

Follows 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>"; 
?>

http://pastebin.com/Tq0kLDxk

1 answer

5

XML Generated manually

I did not understand the difficulty, since it is you 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 indentation level;

  • The \n is the line break.

See working on IDEONE.


General solution with DOM

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

$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;

Upshot:

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

See working on IDEONE.

  • I am beginner, so the difficulty, the tutorials of the net did not tell me about t n, thank you very much for the help.

  • 1

    @Leonardo gives a read on [tour] and see that you can accept an answer that solved your problem. Soon you can vote on everything on the site.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.