Skip to content

Instantly share code, notes, and snippets.

@odan
Last active March 29, 2024 09:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save odan/713515f941bb3b109e461979589ab45f to your computer and use it in GitHub Desktop.
Save odan/713515f941bb3b109e461979589ab45f to your computer and use it in GitHub Desktop.
Remove all namespaces from XML in PHP (dirty hack)
<?php
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML(file_get_contents(__DIR__ . '/demo.xml'));
$dom = removeAllNamespaces($dom);
$dom->save('demo-out.xml');
function removeAllNamespaces(DOMDocument $domSource): DOMDocument
{
$dom = new DOMDocument();
$dom->formatOutput = true;
$domSource = clone $domSource;
$domSource->formatOutput = true;
$dom->loadXML(preg_replace('/\sxmlns="(.*?)"/', '', $domSource->saveXML()));
$xpath = new DOMXPath($dom);
/** @var \DOMNameSpaceNode|DOMAttr $namespaceNode */
foreach ($xpath->query('//namespace::*') as $namespaceNode) {
$prefix = str_replace('xmlns:', '', $namespaceNode->nodeName);
$nodes = $xpath->query("//*[namespace::{$prefix}]");
/** @var DOMElement $node */
foreach ($nodes as $node) {
$namespaceUri = $node->lookupNamespaceURI($prefix);
$node->removeAttributeNS($namespaceUri, $prefix);
}
}
// Important: Reload document to remove invalid xpath references from old dom
$dom->loadXML($dom->saveXML());
return $dom;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment