Skip to content

Instantly share code, notes, and snippets.

@bxt
Created February 27, 2011 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/846139 to your computer and use it in GitHub Desktop.
Save bxt/846139 to your computer and use it in GitHub Desktop.
PHP-Script to auto-format (valid) XML using PHP's DOM
#!/usr/bin/php5
<?php
if (!isset($argv)||$argc!=2||$argv[1]=='-h'||$argv[1]=='--help') {
echo <<<EOH
usage :
formatXMLNicely.php unformated.xml > formated.xml
EOH;
} else {
$file=$argv[1];
if (file_exists($file)) {
if (is_file($file)) {
$xml = simplexml_load_file($argv[1]);
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
if ($domnode = dom_import_simplexml($xml)) {
$domnode = $doc->importNode($domnode, true);
$domnode = $doc->appendChild($domnode);
echo $doc->saveXML();
} else {print ("Error while parsing. \n");}
} else {echo "Error: \"$file\" is a directory. \n";}
} else {echo "Error: No such file or directory: \"$file\" \n";}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment