note 75945 modified in function.simplexml-element-asXML by danbrown
| From: | danbrown@php.net | Date: | Wed, 16 Sep 2009 15:42:09 +0000 |
| Subject: | note 75945 modified in function.simplexml-element-asXML by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-160651@lists.php.net to get a copy of this message | ||
When trying to use the DOMDocument method for pretty printing the output of asXML be careful how you
format the starting XML string. It cannot have spaces or other hidden chars "\n". I also
had trouble with using different types of quotes for the starting XML, but I am unable to replicate
that. So if you cannot get this to work then you might try swapping the single and double quotes.
<?php
$no_spaces = '<?xml version="1.0"
encoding="UTF-8"?><Example></Example>';
$one_space = '<?xml version="1.0" encoding="UTF-8"?><Example>
</Example>';
echo printy($no_spaces);
/* Outputs
<?xml version="1.0"?>
<Example>
<poop from="Myself">
<smell>stinky</smell>
</poop>
</Example>
*/
echo printy($one_space);
/* Outputs... note the space...
<?xml version="1.0"?>
<Example> <poop
from="Myself"><smell>stinky</smell></poop></Example>
*/
function printy($xmlstr){// a combination from the comments below...
$xml = new SimpleXMLElement($xmlstr);
$poop = $xml->addChild("poop");
$poop->addAttribute("from", "Myself");
$poop->addChild("smell", "stinky");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$domnode = dom_import_simplexml($xml);
$domnode = $doc->importNode($domnode, true);
$domnode = $doc->appendChild($domnode);
return $doc->saveXML();
}
?>
--was--
When trying to use the DOMDocument method for pretty printing the output of asXML be careful how you
format the starting XML string. It cannot have spaces or other hidden chars "\n". I also
had trouble with using different types of quotes for the starting XML, but I am unable to replicate
that. So if you cannot get this to work then you might try swapping the single and double quotes.
<?php
$no_spaces = '<?xml version="1.0"
encoding="UTF-8"?><Example></Example>';
$one_space = '<?xml version="1.0" encoding="UTF-8"?><Example>
</Example>';
echo printy($no_spaces);
/* Outputs
<?xml version="1.0"?>
<Example>
<poop from="Myself">
<smell>stinky</smell>
</poop>
</Example>
*/
echo printy($one_space);
/* Outputs... note the space...
<?xml version="1.0"?>
<Example> <poop
from="Myself"><smell>stinky</smell></poop></Example>
*/
function printy($xmlstr){// a combination from the comments below...
$xml = new SimpleXMLElement($xmlstr);
$poop = $xml->addChild("poop");
$poop->addAttribute("from", "Myself");
$poop->addChild("smell", "stinky");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$domnode = dom_import_simplexml($xml);
$domnode = $doc->importNode($domnode, true);
$domnode = $doc->appendChild($domnode);
return $doc->saveXML();
}
?>
http://php.net/manual/en/function.simplexml-element-asXML.php