Using Dom Objects in PHP, the default namespace is updated in some nodes

I am working on a template engine by moving from a regular expression controlled by the DOM. However, it seems that whenever I create DomDocumentFragmentto encapsulate some part of the document temporarily, a namespace attribute is added to each node in the fragment. Since my default namespace for this document will be XHTML 99% of the time, it adds an XHTML namespace declaration.

Being the default namespace, this seems barren, and eventually nodes in any other namespace will be deleted during rendering.

Besides iteratively deleting namespace attributes, is there any way I can prevent this from happening? This is quite problematic, as it is likely to significantly increase the size of the time file, since large fragments of this document can be saved in a fragment.

I tried $doc->normalizeDocument(), but, as I expected, did nothing.

+3
source share
1 answer

Depending on your tolerance for extra computing, in order to solve what is mainly an aesthetic problem (I say mainly because I agree that it takes up extra space for nothing, but other than that everything is fine), you can run your whole XML through an XSL identity template.

, , :

<?php

$xmlIdentityTemplate = '<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>';

$xmlExample = '<?xml version="1.0"?>
<ns1:root xmlns:ns1="urn:ns1" xmlns:ns2="urn:ns2">
    <ns1:node1>
        <ns2:subnode1 xmlns:ns2="urn:ns2">node1 subnode1</ns2:subnode1>
        <ns2:subnode2 xmlns:ns2="urn:ns2">node1 subnode2</ns2:subnode2>
        <ns2:subnode3 xmlns:ns2="urn:ns2">node1 subnode3</ns2:subnode3>
        <ns2:subnode4 xmlns:ns2="urn:ns2">node1 subnode4</ns2:subnode4>
    </ns1:node1>
    <ns1:node2>
        <ns2:subnode1 xmlns:ns2="urn:ns2">node2 subnode1</ns2:subnode1>
        <ns2:subnode2 xmlns:ns2="urn:ns2">node2 subnode2</ns2:subnode2>
        <ns2:subnode3 xmlns:ns2="urn:ns2">node2 subnode3</ns2:subnode3>
        <ns2:subnode4 xmlns:ns2="urn:ns2">node2 subnode4</ns2:subnode4>
    </ns1:node2>
</ns1:root>';

$originalDocument = new DOMDocument();
$originalDocument->loadXML($xmlExample);

$xslDocument = new DOMDocument();
$xslDocument->loadXML($xmlIdentityTemplate);

$processor = new XSLTProcessor();
$processor->importStyleSheet($xslDocument);
$resultDocument = $processor->transformToDoc($originalDocument);

echo "<h1>Before:</h1>";
echo "<pre>" . htmlentities($originalDocument->saveXML()) . "</pre>";
echo "<h1>After:</h1>";
echo "<pre>" . htmlentities($resultDocument->saveXML()) . "</pre>";
+2

Source: https://habr.com/ru/post/1784148/


All Articles