Skip to content

Instantly share code, notes, and snippets.

@craiga
Last active October 6, 2015 04:08
Show Gist options
  • Save craiga/2934093 to your computer and use it in GitHub Desktop.
Save craiga/2934093 to your computer and use it in GitHub Desktop.
printXml
<?php
/**
* Print some XML.
*
* FIXME: This probably doesn't do a good job at prettifying whitespace when supplied with a DOMNode.
*
* @author Craig Anderson <[email protected]>
* @link https://gist.github.com/2934093
*/
function printXml($xml, $echo = true)
{
if(is_string($xml))
{
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false; // need to do this before loading xml
if(!$doc->loadXML($xml))
{
throw new InvalidArgumentException("String is not valid XML");
}
$xml = $doc;
}
if(!$xml instanceof DOMNode)
{
throw new InvalidArgumentException("Argument not recognised as XML");
}
$doc = $xml->ownerDocument;
if(!$doc && $xml instanceof DOMDocument)
{
$doc = $xml;
}
$originalPreserveWhiteSpace = $doc->preserveWhiteSpace;
$originalFormatOutput = $doc->formatOutput;
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$result = sprintf("%s\n", $doc->saveXML($xml));
if($echo) {
echo $result;
}
$doc->preserveWhiteSpace = $originalPreserveWhiteSpace;
$doc->formatOutput = $originalFormatOutput;
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment