Here are the codes:
$doc = new DomDocument('1.0'); // create root node $root = $doc->createElement('root'); $root = $doc->appendChild($root); $signed_values = array('a' => 'eee', 'b' => 'sd', 'c' => 'df'); // process one row at a time foreach ($signed_values as $key => $val) { // add node for each row $occ = $doc->createElement('error'); $occ = $root->appendChild($occ); // add a child node for each field foreach ($signed_values as $fieldname => $fieldvalue) { $child = $doc->createElement($fieldname); $child = $occ->appendChild($child); $value = $doc->createTextNode($fieldvalue); $value = $child->appendChild($value); } } // get completed xml document $xml_string = $doc->saveXML() ; echo $xml_string;
If I print it in the browser I don't get nice XML structure like
<xml> \n tab <child> etc.
I just get
<xml><child>ee</child></xml>
And I want to be utf-8 How is this all possible to do?
Click File > Save As, and select the location where you want to save the file. , point to the arrow next to Save As, and then click Other Formats. In the File name box, type a name for the XML data file. In the Save as type list, click XML Data, and click Save.
Loading an XML String or File With SimpleXML For example, if you want to parse the XML file, you can use the simplexml_load_file() function. The simplexml_load_file() function allows you to read and parse the XML file in a single call.
Of course you can.
You can try to do this:
... // get completed xml document $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $xml_string = $doc->saveXML(); echo $xml_string;
You can make set these parameter right after you've created the DOMDocument
as well:
$doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true;
That's probably more concise. Output in both cases is (Demo):
<?xml version="1.0"?> <root> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> </root>
I'm not aware how to change the indentation character(s) with DOMDocument
. You could post-process the XML with a line-by-line regular-expression based replacing (e.g. with preg_replace
):
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
Alternatively, there is the tidy extension with tidy_repair_string
which can pretty print XML data as well. It's possible to specify indentation levels with it, however tidy will never output tabs.
tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With