Last active
March 29, 2024 09:34
-
-
Save odan/713515f941bb3b109e461979589ab45f to your computer and use it in GitHub Desktop.
Remove all namespaces from XML in PHP (dirty hack)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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